【发布时间】:2018-11-18 05:19:36
【问题描述】:
我正在学习 rxjs,我想我做错了什么,因为我的 BehaviourSubject 只发出一次值。
在我的服务中 -
private cartItemCount = new BehaviorSubject<Observable<Number>>(this.getCartItemsCount());
actualCartItemCount=this.cartItemCount.getValue();
getCartItemsCount(){
return this.http.get<Number>('/api/getCartItemsCount/'+this.getCartID());
}
Below Method 也在上述添加或删除产品的服务中,但将从 ProductCartComponent 调用,并且在内部我调用 Behavior Subject 的下一个方法
private updateProductCart(cartID:string,productId:number,change:string){
this.cartItemCount.next(this.getCartItemsCount());
return this.http.get<Item>('api/updateProductItem/'+cartID+'/'+productId+'/'+change);
}
现在在我的 NavBar 组件中,我订阅了 actualCartItemCount Observable
constructor( private cartService:ShopingCartService)
{ }
ngOnInit() {
this.cartService.actualCartItemCount.
subscribe(res => {this.totalCartItemCount = res;
}
在控制台中,我可以看到 getCartItemsCount 会在添加或删除发生时被调用,但在我订阅了 actualCartItemCount 的 NavBar 组件中只会被调用一次。
请指导我,如果需要更多详细信息,请告诉我...
【问题讨论】:
-
我猜你有两个不同的服务实例。向我们展示您提供服务的方式和地点(即您在哪里拥有
providers: [ShopingCartService]。 -
在 app.module.ts 我有以下数组,所有的服务都是这样提到的 - providers: [SignUpService, ShopingCartService, AuthGuard, LoginGuard,{提供:HTTP_INTERCEPTORS, useClass:AuthInterceptor, multi:true }],
-
您可能正在破坏
subscription的某个地方,例如ngDestroy或其他地方,以至于它没有得到 -
在
this.cartItemCount.getValue()你有来自this.getCartItemsCount()的返回值,它只创建一次。那么订阅this.cartService.actualCartItemCount就是订阅this.http.get而不是BehaviorSubject。 -
是的@martin,你是对的...我不能在 this.cartItemCount 上使用 .asObservable,因为它已经是 Observable
所以我继续这样做..
标签: angular rxjs behaviorsubject