首页 > 解决方案 > 多次单击按钮时的Angular 6订阅清理

问题描述

假设我有一个订阅联系我们服务的联系我们按钮,该按钮在触发 http 请求后返回一个 observable。

如果用户点击按钮 10 次并发送 10 封电子邮件(需要),是否会同时运行 10 个订阅?如果是这样,在这种情况下订阅清理的最佳做法是什么?

标签: angularrxjs

解决方案


只需将您的订阅保存在属性中并检查它是否存在,不要订阅,如果不订阅,则

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
    });
}

推荐阅读