Reputation: 185
I'm trying fetch data via REST with angular 2 HttpClient
basket.component.ts
ngOnInit() {
this.cart = this.shoppingCartService.get();
this.cartSubscription = this.cart.subscribe((cart) => {
this.itemCount = cart.items
.map((x) => x.quantity)
.reduce((p, n) => p + n, 0);
this.cartItems = cart.items.map((item) => {
let product = {};
product = this.productsService.find_p(item.productId);
return {...item,product}
});
});
}
basket.component.html
<tbody *ngIf='cartItems'>
<tr *ngFor="let item of cartItems">
<td>
<i class="fa fa-trash-o" aria-hidden="true" (click)='removeItem(item.productId)' style="font-size: 21px;color:red;"></i>
</td>
<td>
<img class="uk-preserve-width uk-border-circle" src="assets/images/fish.png" width="40" alt="">
</td>
<td class="uk-table-link">
<a class="uk-link-reset" *ngIf='item.product.product' href="">{{ item.product.product.name }}</a>
</td>
<td class="uk-text-nowrap">{{ item.quantity }}</td>
<td class="uk-text-nowrap">۲۵۰۰۰ هزارتومان</td>
<td class="uk-text-nowrap">ZF-3268</td>
</tr>
</tbody>
but i cant fetch result i think my callback data is text not json but i dont know how to fix it
on inspect element
ERROR TypeError: Cannot read property 'product' of undefined
product log
product : Observable operator : CatchOperator {selector: ƒ, caught: Observable} source : Observable {_isScalar: false, source: Observable, operator: MapOperator} _isScalar : false proto : Object
and my product service
find_p(id) {
let url: string = `${this.BASE_URL}/product/${id}.json`;
return this.http.get(url, {headers: this.headers}).map((res:Response) => res.json() as [{}] )
//...errors if any
.catch((error:any) => Observable.throw(error.json().error || 'Server error'));
}
When I did that the .json() method was been resolved but another error popped up that
Property results does not exist on type Promise or observable
Upvotes: 0
Views: 341
Reputation: 58603
Issue with your code is find_p
returning Observable
not the product data
product = this.productsService.find_p(item.productId);
And you are using product
as data on template side.
Solution :
Replace this code block
this.cartItems = cart.items.map((item) => {
let product = {};
product = this.productsService.find_p(item.productId);
return {...item,product}
});
With :
let observerArray = [];
cart.items.forEach((item) => {
observerArray.push(this.productsService.find_p(item.productId));
});
Observable.forkJoin(observerArray).subscribe(products => {
this.cartItems = cart.items.map((item,index) => {
return {...item,product : products[index]}
});
});
Upvotes: 1