【发布时间】: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上提供一个工作示例吗?