如何订阅和取消订阅可观察对象?

时间:2019-05-27 13:07:25

标签: angular rxjs angular2-observables

我有两个功能,我需要在第一个中订阅一个可观察对象,然后在第二个中取消订阅。但是在我的代码中,我无法从第二个函数访问可观察对象,因为它不在其范围内。

这是我的功能:

 start() {
    this.max = this.duration;
    const interval = Observable.interval(this.selectedSprint.duration);
    interval
      .takeWhile(_ => !this.isFinished)
      .do(i => this.current += 1)
      .subscribe();
    }

    stop() {
    // here I need to unsybscribe to the observable
    this.dialogService.openConfirmDialog('do you want to stop ?')
      .afterClosed().subscribe((result: boolean) => {
        if (result) {
    // if true logic
        }
      });
      }

3 个答案:

答案 0 :(得分:2)

使用this.sub = interval.[...].subscribe()在班级中保存对您的订阅的引用。

这样,您就无法在第二个功能中调用this.sub.unsubscribe()

答案 1 :(得分:2)

一种解决方案是将订阅存储在组件中。

export class Component {
  interval$: Subscription;

  start() {
    this.max = this.duration;
    this.interval$ = Observable.interval(this.selectedSprint.duration)
      .takeWhile(_ => !this.isFinished)
      .do(i => this.current += 1)
      .subscribe();
  }

  stop() {
    // here I need to unsybscribe to the observable
    this.dialogService.openConfirmDialog('do you want to stop ?')
      .afterClosed().subscribe((result: boolean) => {
        if (result) {
          this.interval$.unsubscribe();
        }
    });
  }
}

编辑以回答OP的评论

export class Component {
  intervalSub$: Subscription;
  intervalObs: Observable<number>;

  start() {
    this.max = this.duration;
    this.intervalObs$ = Observable.interval(this.selectedSprint.duration)
      .takeWhile(_ => !this.isFinished)
      .do(i => this.current += 1);
   this.intervalSub$ = intervalObs.subscribe();
  }

  stop() {
    // here I need to unsybscribe to the observable
    this.dialogService.openConfirmDialog('do you want to stop ?')
      .afterClosed().subscribe((result: boolean) => {
        if (result) {
          this.intervalSub$.unsubscribe();
        }
    });
  }
  /**
   * If you unsubscribed from the interval and you want to resume
   * (If this.isFinished is true, it won't do a thing)
   */
  resume() {
    this.intervalObs.subscribe();
  }
}

答案 2 :(得分:0)

如果您在上课,则可以将subscription的调用返回的.subscribe()对象作为属性。

start() {
   this.max = this.duration;
   const interval = Observable.interval(this.selectedSprint.duration);
   interval
     .takeWhile(_ => !this.isFinished)
     .do(i => this.current += 1);
   this.intervalSubscription = interval.subscribe();
}

这将使您可以退订stop方法

stop() {
    this.intervalSubscription.unsubscribe(...);
}
相关问题