【问题标题】:shareService in angular 2 - twice subscribe the next function角度 2 中的 shareService - 两次订阅下一个函数
【发布时间】: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


【解决方案1】:

正如 cmets 中所讨论的,这可能是由于多个订阅。要验证不是这样,您可以在订阅上方添加以下行:

console.log('pre subscribe, number of observers is: ', _shareService.ShopItem$_.source.observers.length);

注意这适用于 rxjs 4,在版本 5 中您可能需要不同的语法。

它应该给你 0,如果你得到另一个值,你已经有一个活跃的订阅。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-12
    • 2016-10-07
    • 1970-01-01
    • 1970-01-01
    • 2023-01-01
    • 2021-01-10
    • 1970-01-01
    相关资源
    最近更新 更多