【发布时间】:2016-10-05 21:15:44
【问题描述】:
我在 Angular 2 中有一个 ShareService,在另一个组件中我订阅了它,这是我的代码:
*******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 没有任何问题,我使用函数对其进行测试并执行一次。
【问题讨论】:
-
您的应用程序中是否有多个“另一个组件”实例?
-
不,这是我第一次遇到这样的问题!无法解决:((
-
ShopItem$.next()被调用两次或者有两个订阅者。 -
不,我检查了,当用户单击按钮时,我有一个按钮,只需 ShopItem$.next(item) 函数执行一次...我检查所有组件,但没有另一个 ShopItem$。下一个(项目)
-
您能在
addToCart()中添加一些console.log(item)以查看它被调用的频率吗?
标签: javascript angularjs typescript angular rxjs