角度2中的shareService-两次订阅下一个函数 [英] shareService in angular 2 - twice subscribe the next function
问题描述
我在角度2中有一个ShareService,在另一个组件中,我订阅了它,这是我的代码:
I have a ShareService in angular 2,and in another component i subscribe that,and this is my code :
*******ShareService ***********************************
private ShopItem$ = new Subject<any>();
ShopItem$_ = this.ShopItem$.asObservable();
public addToCart(item : any){
this.ShopItem$.next(item);
}
*************in another component**********************
_shareService.ShopItem$_.subscribe((item) => {
alert("hiii"); <====>this functions execute twice
this.ADD_TO_CART(item);<====>this functions execute twice
});
我的问题是ADD_TO_CART()函数执行两次!为什么?我不希望我的购物车函数执行两次,如何解决此问题?ShareService没问题,我可以使用一个函数对其进行测试,然后执行.
my problem is ADD_TO_CART() function execute twice!why?i dont want my cart function execute twice,how to fix this problem?? the ShareService dont have any problem i test it with an function and once execute.
推荐答案
如注释中所述,这可能是由于多个订阅所致.要验证不是这样,您可以将您的订阅放在下面,即下面的行:
As discussed in the comments, this is probably due to multiple subscriptions. To verify it is not this, you can put just above your subscriptions, the following line:
console.log('pre subscribe, number of observers is: ', _shareService.ShopItem$_.source.observers.length);
注意,该功能适用于rxjs 4,在版本5中,您可能需要使用其他语法.
Note this works on rxjs 4, in version 5 you might need a different syntax.
应该给您0,如果您获得另一个值,则您已经有一个有效的订阅.
It should give you 0, if you get another value, you have an already active subscription.
这篇关于角度2中的shareService-两次订阅下一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!