【问题标题】:"this" is undefined in ngOnDestroy“this”在 ngOnDestroy 中未定义
【发布时间】:2022-01-05 22:00:41
【问题描述】:

我正在尝试取消订阅组件的ngOnDestroy 方法,但this 的实例已经是undefined

import { Component, OnDestroy, OnInit } from '@angular/core';
import { SomeService} from 'somewhere';
import { Subscription } from 'rxjs';

@Component({
  ...
})
export class SomeComponent implements OnInit, OnDestroy {
  subscription: Subscription | undefined;

  constructor(
    private someService: SomeService
  ) {}

  ngOnInit(): void {
    this.subscription = new Subscription();
  }

  ngOnDestroy(): void {
    console.log(this);  // **log shows that 'this' is 'undefined'**

    if (this?.subscription) 
      this.subscription.unsubscribe();
  }
   
  onNextClick() {
    this.subscription = this.someService
      .getSomething()
      .subscribe({
        next: (res) => {
          console.log('HTTP response', res);
        },
        error: (err: unknown) => {
          console.log('HTTP Error', err);
        },
        complete: () => console.log('HTTP request completed.'),
      });
  }
}

getSomethig 服务的方法返回一个我订阅的 Observable。我想在 OnDestroy 事件中关闭该订阅,但到那时 this 对象已经未定义并且订阅不再存在。

网上很多例子都展示了这种取消订阅的方式,但是订阅通常是在 OnInint 事件中完成的。就我而言,事件发生在单击按钮后。

在这种情况下我应该如何退订?

【问题讨论】:

  • 你能在stackblitz上提供一个工作示例吗?

标签: angular ondestroy


【解决方案1】:

用 TakeUntil 试试这个方法:

import { Component, OnDestroy, OnInit } from '@angular/core';
import { SomeService} from 'somewhere';
import { Subscription } from 'rxjs';

@Component({
  ...
})
export class SomeComponent implements OnInit, OnDestroy {
   destroy$: Subject<boolean> = new Subject<boolean>();
  constructor(
    private someService: SomeService
  ) {}

  ngOnInit(): void {
  }

  ngOnDestroy(): void {
   this.destroy$.next(true);
   this.destroy$.unsubscribe();
  }
   
  onNextClick() {
     this.someService
      .getSomething().pipe(
      takeUntil(this.destroy$)
    ).subscribe({
        next: (res) => {
          console.log('HTTP response', res);
        },
        error: (err: unknown) => {
          console.log('HTTP Error', err);
        },
        complete: () => console.log('HTTP request completed.'),
      });
  }
}
    

【讨论】:

  • 在ngOnDestory()方法中,你应该先调用next()然后调用complete()而不是unsubscribe(),像这样:this.destroy$.next(); this.destroy$.complete();
  • 我试过这个解决方案,结果是一样的。 'this' 仍然未定义,因此 destroy$ 在这种情况下也不可用。
  • @Tschareck 你能告诉我为什么要安慰这个吗?因为代码执行得很好,如果你的组件会破坏你将取消订阅 observable
猜你喜欢
  • 2016-04-03
  • 2019-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-21
  • 2018-10-06
  • 2020-03-03
相关资源
最近更新 更多