我正在尝试用角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: false proto:Object
以及我的产品服务
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()方法被解析了,但是出现了另一个错误
性质的结果在类型承诺或可观察的上不存在
发布于 2018-01-12 11:58:56
代码的问题是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]}
});
});https://stackoverflow.com/questions/48225412
复制相似问题