提问者:小点点

“this”在ngOnDestroy中未定义


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

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.'),
      });
  }
}

该服务的get一些方法返回一个可观察的,我订阅。我想在OnDestroy事件中关闭该订阅,但是到那时这个对象已经未定义,订阅不再存在。

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

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


共1个答案

匿名用户

尝试这种方式与取直到:

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.'),
      });
  }
}