【问题标题】:How to unsubscribe from not initialized subscription in Angular如何取消订阅Angular中未初始化的订阅
【发布时间】:2019-01-29 05:04:18
【问题描述】:

我收到以下错误:

ERROR 错误:未捕获(承诺中):TypeError:无法读取未定义的属性“取消订阅”

我的订阅不在 ngOnInit 上,这就是我收到此错误的原因,因为我持有订阅的属性尚未初始化,但在这种情况下“正确的方法”是什么。

这是我的代码:

【问题讨论】:

  • 在退订前检查sub是否存在。使用 if 语句。
  • 您取消订阅尚未初始化的对象。尝试在取消订阅之前检查 this.sub 是否已定义。
  • 删除一个变量 isAlive = true; 然后删除 sub 并使用 rxJs 中的 takeWhile:this.authService.login(this.login.form.value).takeWhile(() => this.isAlive).subscribe(...); in the onDestroy: this.isAlive = false;`
  • 将订阅分配给一个变量并检查它是否已定义。题外话:不要用图片来展示代码。
  • 私人订阅:Subscription = new Subscription();

标签: angular


【解决方案1】:

在订阅 observable 之前,您可以使用 rxjstakeUntil() 运算符和 pipe()

 unsubscribeSignal: Subject<void> = new Subject();

 ngOnInit() {
    this.subscription = this.observableToSubscribe
    .pipe(
       takeUntil(this.unsubscribeSignal.asObservable()),
    )
    .subscribe(result => {

      //Do some fancy stuff here

      console.log(result );
    });
  }

  ngOnDestroy(){
    this.unsubscribeSignal.next();
  }

使用takeUntil 而不是手动取消订阅的另一个好处是您可以使用单个Subject 一次取消订阅多个订阅。

你可以看看我的另一个答案here

【讨论】:

  • 谢谢你,这行得通。我还有一个问题。你的代码和如果我跳过管道有什么区别,所以只需在 observableToSubscribe 之后链接 takeUntil?
  • 不客气。 AFAIK,使用最新版本的 RxJS (v6.x),takeUntil 成为可管道操作符,只能在 pipe 方法中使用。
猜你喜欢
  • 2022-01-19
  • 2012-03-14
  • 2018-04-19
  • 2021-11-18
  • 1970-01-01
  • 1970-01-01
  • 2015-08-24
  • 2019-12-05
  • 1970-01-01
相关资源
最近更新 更多