Angular 获取 JSON 对象并用 HTML 显示
我有一个像这样的 JSON 对象:
{
"cartId": 1,
"cartName": "Cart",
"CartItems": [
{
"productId": 1,
"product": {
"productId": 1,
"productName": "milk",
"price": 3.0,
"categoryId": 1,
},
"price": 3.0,
"quantity": 4,
"subTotal": 12.0
},
{
"productId": 2,
"product": {
"productId": 2,
"productName": "oranges",
"price": 3.0,
"categoryId": 5,
},
"price": 3.0,
"quantity": 6,
"subTotal": 18.0
}
],
"grandTotal": 30.0
}
这是我的服务:
getCart(): Observable<Cart[]> {
return this.http.get<Cart[]>(this.myAppUrl + this.myApiUrl)
.pipe(
retry(1)
);
}
这是我的组件:
cart$: Observable<Cart[]>;
constructor(private cart_Service: CartService,private http: HttpClient) {
}
ngOnInit() {
this.loadCart();
}
loadCart() {
this.cart$ = this.cart_Service.getCart();
}
我想在 cart.component.html 文件中像这样获取 grandTotal:
<p *ngIf="!(cart$ | async)"><em></em></p>
<table class="table table-sm table-hover" >
<thead>
<tr>
<th> Grand Total</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let i of (cart$ | async)">
<td>{{ i.grandTotal }}</td>
</tr>
</tbody>
但是我收到错误提示,说“NgFor 仅支持绑定到诸如数组之类的可迭代对象。”我尝试了不同的解决方案将我的 JSON 对象转换为 TypeScript 数组,但都没有帮助。有人能帮我捕获 grandTotal 并在我的 Web API 中使用 HTML 显示它吗?我认为我们需要数组才能获取该 grandTotal。
答案#1
你可以尝试这个
return this.http.get<Cart[]>(this.myAppUrl + this.myApiUrl)
.pipe(
map(response => response as unknows as Cart[])
retry(1)
);
或
将响应映射为 Cart[]
答案#2
我终于解决了这个。这是我的服务
getCart(): Observable<Cart[]> {
return this.http.get<Cart[]>(this.myAppUrl + this.myApiUrl);
}
这是我的组件:
my_data: any;
public loadCart() {
this.cart_Service.getCart().subscribe((data: Cart[]) => this.my_data = data);
}
这是我的 HTML:
<div>
<p> Grand Total : {{ my_data.grandTotal }} </p>
</div>
