我使用Observable.forkjoin发送多个http请求并将结果存储在变量中,但我无法访问html中的结果。请任何人帮忙。
Service.ts:
addedProductIdArray : string[] =[];
reqs = [];
constructor(private _http: Http){};
getAddedProducts() {
for(var i = 0; i < this.addedProductIdArray.length; i++){
this.reqs.push(this._http.get("https://my-json-server.typicode.com/shopping-cart/"+this.addedProductIdArray[i])
.map((res: any) => res.json()));
}
return Observable.forkJoin(this.reqs);
}
Component.ts
products : IProduct[];
constructor(private _cartService : CartService) {
this._cartService.getAddedProducts().subscribe((data: IProduct[]) => {
this.products = data;
});
};
Component.html:
<ng-container *ngFor="let product of products">
<a>{{product.title}}</a>
</ng-container>
我的html中的product.title为空。请帮忙
答案 0 :(得分:0)
在检查共享网址中的响应时,我发现在您使用map
目前的回应如下:
headers:Headers {_headers: Map(4), _normalizedNames: Map(4)}
ok:true
status:200
statusText:"OK"
type:2
url:"https://my-json-server.typicode.com/AnifaMd/shopping-cart/ec1040"
_body:"[↵ {↵ "title": "Common Projects Bball High ",↵ "id": "ec1040",↵ "color": "White",↵ "price": 540,↵ "availability": "Available"↵ }↵]"
虽然它应该是:
[
{
"title": "Common Projects Bball High ",
"id": "ec1040",
"color": "White",
"price": 540,
"availability": "Available"
}
]
响应是数组的数组,因此您必须按以下方式修改它:
this._cartService.getAddedProducts().subscribe((data) => {
this.products = data.map(item => item[0]);
});
这样可行。
答案 1 :(得分:0)
service.ts和component.ts中的函数没有任何问题。 您收到的回复如下。
[
[{
"title": "Common Projects Bball High ",
"id": "ec1040",
"color": "White",
"price": 540,
"availability": "Available"
}],
[{
"title": "Maison Margiela Future Sneakers",
"id": "ec1041",
"color": "White",
"price": 870,
"availability": "Out of stock"
}],
[{
"title": "Our Legacy Brushed Scarf",
"id": "ec1042",
"color": "Brown",
"price": 349,
"availability": "Available"
}]
]
因此,您必须稍微更改component.html,如下所示。
<ng-container *ngFor="let product of products">
<ng-container>
<div class="col-lg-4 col-md-6 mb-4" *ngFor="let item of product">
<div class="card h-100">
<div class="card-body">
<h4 class="card-title">
<a>{{item.title}}</a>
</h4>
<h5>{{item.price | currency:'INR'}}</h5>
<p class="card-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet numquam aspernatur!</p>
</div>
<div class="card-footer">
{{item.availability }}
</div>
</div>
</div>
</ng-container>
</ng-container>
我希望这能解决您的问题。如果您仍有问题,请告诉我。