在component中实现OnDestroy接口并在其中取消订阅,以确保组件被正确摧毁并可以重新初始化。
示例代码:
import { Component, OnDestroy } from '@angular/core'; import { Subscription } from 'rxjs';
@Component({
selector: 'app-my-component',
template:
,
})
export class MyComponent implements OnDestroy {
private subscription: Subscription;
constructor() { this.subscription = someObservable.subscribe(); }
ngOnDestroy() { this.subscription.unsubscribe(); } }