【发布时间】:2018-12-19 06:14:41
【问题描述】:
我正在开发 Angular 6 中的电子商务应用程序。我想更新标题组件中的购物车计数,当产品从购物车中添加/删除时。如果我刷新页面,两者都是不同的组件,那么只有购物车计数已更新。我尝试了共享服务在这两个组件之间共享数据并尝试了主题概念,但未能自动获取计数。如何实现?
购物车服务.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 没有得到所需的输出。
【问题讨论】:
-
为什么不只使用 observables?尝试从
getCart()返回 Observable。 -
我无法得到你。如何从 getCart() 返回 Observable。
-
您在那里尝试的链接也服务方法返回类型是可观察的。 Observables 和 Promises 是不同的angular.io/guide/…
-
我要求使用promise。如果有任何方法可以使用promise。
标签: angular