在Angular Elements组件中,我们通常会使用ngOnInit
订阅一些Observable对象,这些订阅需要在组件销毁时手动取消。因此,我们需要在ngOnDestroy生命周期方法中手动取消订阅。
以下是示例代码:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-my-angular-element',
template: `My Angular Element`
})
export class MyAngularElementComponent implements OnInit, OnDestroy {
private sub: Subscription = new Subscription();
ngOnInit() {
this.sub = someObservable.subscribe(data => {
console.log(data);
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
}
Zone.js是一个非常有用的库,可以跟踪所有异步操作,包括api调用和DOM事件,并在组件销毁时自动取消所有异步操作。因此,我们可以使用Zone.js来解决内存泄漏问题。
在main.ts中引入zone.js
import 'zone.js/dist/zone.js';
import 'zone.js/dist/zone-error.js';
RxJS中的takeUntil操作符可以帮助我们在组件销毁时自动取消订阅。它需要一个Observable对象作为参数,该对象会在组件销毁时发出一个信号,使订阅自动取消。
以下是示例代码:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
@Component({
selector: 'app-my-angular-element',
template: `My Angular Element`
})
export class MyAngularElementComponent implements OnInit, OnDestroy {
private destroy$: Subject = new Subject();
ngOnInit() {
someObservable.pipe(
takeUntil(this.destroy$)
).subscribe(data => {
console.log(data);
});
}
ngOnDestroy