代码之家  ›  专栏  ›  技术社区  ›  RandomUs1r

Angular 6多次单击按钮时的订阅清理

  •  0
  • RandomUs1r  · 技术社区  · 6 年前

    假设我有一个“联系我们”按钮,订阅了一个“联系我们”服务,它在触发HTTP请求后返回一个observable。

    如果用户点击10次按钮并发送10封电子邮件(需要),那么10个并发订阅会运行吗?如果是,那么在这种情况下,清除订阅的最佳实践是什么?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Drenai    6 年前

    如果添加一个 take(1) 订阅时发送到管道-如果您订阅了多次

    或者,在组件中使用按钮进行单个订阅,在中初始化该按钮。 ngOnInit() 或者在 constructor . 将对订阅的引用保存在 private contactSubscription: SubscriptionLike 属性和调用 contactSubscription && contactSubscription.unsubscribe 在里面 ngOnDestroy()

        2
  •  1
  •   Artyom Amiryan    6 年前

    只需将订阅保存在一个属性中,并检查它是否存在、是否未订阅,如果不存在,则订阅

    cacheSub: Subscription;
    
    contactUs() {
      if(!this.cacheSub) {
         this.cacheSub = this.service.cacheSub.subscribe(....);
      }
    }
    

    编辑

    如果您希望每次订阅并清除每个订阅,那么可以这样做

    cacheSub: Subscription;
    
    contactUs() {
         this.cacheSub = this.service.cacheSub.subscribe(() => {
            // some code here if you need it
            this.cacheSub.unsubscribe();
         });
    }
    

    contactUs() {
        this.cacheSub && this.cacheSub.unsubscribe();
        this.cacheSub = this.service.cacheSub.subscribe(() => {
                // some code here if you need it
        });
    }