簡體   English   中英

“this”在 ngOnDestroy 中未定義

[英]"this" is undefined in ngOnDestroy

我正在嘗試在組件的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 object 已經未定義並且訂閱不再存在。

網上很多例子都展示了這種取消訂閱的方式,但是訂閱通常是在 OnInint 事件中完成的。 就我而言,事件發生在單擊按鈕后。

在這種情況下我應該如何退訂?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM