我可能在某个地方犯了一个愚蠢的错误,但我厌倦了到处寻找,不明白这个问题。我试图显示对表的api响应,但没有显示任何内容。
My在响应之后返回
[{"productId":1,"productName":"tomato","productPrice":200,"productQuantity":5,"catId":1},{"productId":2,"productName":"potato","productPrice":33,"productQuantity":44,"catId":2}]
我的服务类
import { Injectable, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Iproducts } from '../model-ts/products';
@Injectable({
providedIn: 'root'
})
export class GetprodlistService {
myAppUrl: string = "";
constructor(private http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
this.myAppUrl = baseUrl;
}
getproducts(): Observable<Iproducts[]> {
return this.http.get<Iproducts[]>(this.myAppUrl + 'api/admin/manageproducts/getproducts');
}
}Iproducts接口类
export interface Iproducts {
ProductId: number,
ProductName: string,
ProductPrice: number,
ProductQuantity: number,
CatId: number
}Compoenent.ts文件是:
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { GetprodlistService } from '../../Services/getprodlist.service';
@Component({
selector: 'app-manage-products',
templateUrl: './manage-products.component.html',
styleUrls: ['./manage-products.component.css']
})
export class ManageProductsComponent implements OnInit {
constructor(public http: HttpClient, public productservice: GetprodlistService) {
this.getproducts();
}
public prodlist = [];
getproducts() {
this.productservice.getproducts().subscribe(
data => this.prodlist=data);
console.log("product list: " + this.prodlist)
}
ngOnInit(): void {
}
}我的Component.html文件是:
<p *ngIf="!prodlist"><em>Loading...</em></p>
<table class='table' *ngIf="prodlist">
<thead>
<tr>
<th>Product ID</th>
<th>Product Name</th>
<th>Product Price</th>
<th>Product Quantity</th>
<th>Category ID</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let prod of prodlist">
<td>{{ prod.ProductId }}</td>
<td>{{ prod.ProductName }}</td>
<td>{{ prod.ProductPrice }}</td>
<td>{{ prod.ProductQuantity }}</td>
<td>{{ prod.CatId }}</td>
</tr>
</tbody>
</table>谢谢
发布于 2020-03-16 16:47:08
您正在以错误的方式访问响应数据的属性。您的类型定义模型也不正确。
类型定义
export interface Iproducts {
productId: number,
productName: string,
productPrice: number,
productQuantity: number,
catId: number
}HTML
<p *ngIf="!prodlist"><em>Loading...</em></p>
<table class='table' *ngIf="prodlist">
<thead>
<tr>
<th>Product ID</th>
<th>Product Name</th>
<th>Product Price</th>
<th>Product Quantity</th>
<th>Category ID</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let prod of prodlist">
<td>{{ prod.productId }}</td>
<td>{{ prod.productName }}</td>
<td>{{ prod.productPrice }}</td>
<td>{{ prod.productQuantity }}</td>
<td>{{ prod.catId }}</td>
</tr>
</tbody>发布于 2020-03-16 16:41:32
Iproducts接口文件中声明的键必须与JSON对象中的键完全匹配。
首先修改接口类的键,以小写字母开头,类似于JSON响应对象。
export interface Iproducts {
productId: number,
productName: string,
productPrice: number,
productQuantity: number,
catId: number
}https://stackoverflow.com/questions/60709666
复制相似问题