我正在开发角度为6.的电子商务应用程序。我要在商品添加到购物车中/从购物车中删除时更新标题组件中的购物车计数。如果我刷新页面,则只有两个购物车计数是两个不同的组件更新。我尝试了共享服务在这两个组件之间共享数据,也尝试了主题概念,但未能自动获得计数。如何实现?
购物车Service.ts:
async getCart():Promise<HttpResponse<Object>> {
const cartItems = await this.httpClient.get<HttpResponse<Object>>(this.endPointService.getCartItemURL, { observe :'response',withCredentials: true })
.toPromise();
return cartItems;
}
header.ts:
cartItem: CartItem[];
ngOnInit() {
const cartItems = <HttpResponse<Object>>await this.cartService.getCart();
this.cartItem = <CartItem[]>cartItems.body;
}
header.html:
<span class='cart_count notification-counter' data-toggle="modal" data-target="#exampleModal">{{cartItem.length}}</span>
尝试的代码:
cartService.ts
private prodCount = 0;
prodCountCountChange: Subject<number> = new Subject<number>();
UpdateCount(count: number) {
this.prodCount = count;
this.prodCountCountChange.next(this.prodCount);
}
header.ts:
cartCount :any;
cartItem: CartItem[];
this.cartCount = this.cartService.UpdateCount(this.cartItem.length);
header.html:
<span class='cart_count notification-counter' data-toggle="modal" data-target="#exampleModal">{{cartCount}}</span>
我也尝试了此链接angular view is not updating after component value gets changed中使用的行为主题未获得所需的输出。
答案 0 :(得分:0)
您没有正确使用Subject,并且Cart服务中的初始getCart()不会返回Promise,而是返回结果。
[编辑]
在stackblitz中可用
购物车Service.ts:
// getCard should return only datas, not an httpResponse object
// and the result should be typed
getCart(): Promise<CartItem[]> {
return this.httpClient.get(
this.endPointService.getCartItemURL,
{ observe :'response',withCredentials: true }
).pipe(
map((httpResponse: HttpResponse<any>) => {
this.updateCount(httpResponse.body.length); // Don't know how your cardItem[] is formatted
return [].concat(httpResponse.body);
})
).toPromise();
}
private prodCount: number = 0;
public prodCountCountChange: Subject<number> = new Subject();
updateCount(count: number = 0): void {
this.prodCount = count;
this.prodCountCountChange.next(this.prodCount);
}
header.ts:
async ngOnInit() {
this.cartItem = await this.cartService.getCart();
this.cartService.prodCountCountChange.subscribe(
newProdCount => this.cartCount = newProdCount
);
}
// and don't forget to unsubscribe
ngOnDestroy() {
this.cartService.prodCountCountChange.unsubscribe();
}
header.html:
<span class='cart_count notification-counter' data-toggle="modal" data-target="#exampleModal">{{cartCount}}</span>
希望有帮助。
答案 1 :(得分:0)
尝试此操作,就像应订阅Observable一样,并应像这样执行Promises。 promise
ngOnInit() {
this.cartService.getCart().then(
(cartItems)=>{
this.cartItem = <CartItem[]>cartItems.body;
}
);
}