【发布时间】:2019-07-12 22:46:22
【问题描述】:
我有角度购物模板,我正在尝试将用于我的后端的购物车服务连接起来,所以我已经这样做了,但是为了使数据库中的事情更容易,我不得不将请求从 {quantity, amount, product} 更改为我的后端到{quantity, amount, productId},所以我不必将整个产品存储在数据库中并且到目前为止它工作正常,现在当我得到响应时,我想将它映射到它的界面,但首先我需要找到带有 id 的产品如果我有整个产品,我可以在响应中映射响应,但我又不想将产品保存在我的数据库中。这是我的映射代码,但我在调用按 id 查找产品的函数时遇到问题:
this.getAllProducts().pipe(map(p => p.map((s): CartItem => ({
currency: s.currency,
product: this.productService.getProduct(s.product).subscribe(p => p),
quantity: s.quantity,
selectedColor: s.selectedColor,
selectedSize: s.selectedSize,
userId: s.userId
}))));
private getAllProducts(): Observable<CartResponse[]> {
return this.http.get<CartResponse[]>('http://localhost:8082/cart/getAllItems?userId=111').pipe(
map(o => o.map((sp): CartResponse => ({
quantity: sp.quantity,
currency: sp.currency,
product: sp.product,
selectedColor: sp.selectedColor,
selectedSize: sp.selectedSize,
userId: sp.userId
}))));
}
export interface CartResponse {
product: string;
quantity: number;
selectedSize: any;
selectedColor: string;
currency: string;
userId: string;
}
export interface CartItem {
product: Product;
quantity: number;
selectedSize: any;
selectedColor: string;
currency: string;
userId: string;
}
【问题讨论】:
-
不需要
getAllProducts方法中的完整map部分。删除它。 -
我不明白的事情:为什么在嵌套的
map调用中处理来自p的元素为CarItem?CartResponse不应该是s的类型吗? -
另外,请添加所用接口的定义,特别是
CartResponse。 -
@Jota.Toledo 我已将接口定义添加到问题中
-
添加了答案:)
标签: angular http rxjs angular-httpclient