我正在尝试使用Angular 2 HttpClient通过REST提取数据
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>
但我无法获取结果,我认为我的回调数据是文本而不是json,但我不知道如何解决它
在检查元素上
错误TypeError:无法读取未定义的属性“产品”
产品日志
产品
:可观察的运算符:CatchOperator {选择器:ƒ,已捕获:
可观察的}来源:可观察的{_isScalar:false,来源:可观察,
运算子:MapOperator}
_isScalar:假
原型:对象
和我的产品服务
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'));
}
当我这样做时,.json()方法已解决,但弹出另一个错误
属性结果在Promise类型或可观察类型上不存在
最佳答案
您代码的问题是find_p
返回Observable
而不是产品数据
product = this.productsService.find_p(item.productId);
而且您正在使用
product
作为模板方面的数据。解决方案:
替换此代码块
this.cartItems = cart.items.map((item) => {
let product = {};
product = this.productsService.find_p(item.productId);
return {...item,product}
});
与:
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]}
});
});
关于javascript - 无法获取 Angular 上的其余结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48225412/