我的 Angular 应用程序有很多组件,其中之一是 MyComponent,其组件类如下所示:
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/interval';
@Component({
selector: 'app-my',
templateUrl: './my.component.html',
styleUrls: ['./my.component.scss']
})
export class MyComponent implements OnInit {
a = 'I still alive';
constructor() {}
ngOnInit() {
Observable.interval(1000).subscribe(x => console.log(this.a));
}
}
Run Code Online (Sandbox Code Playgroud)
如果我访问 MyComponent,订阅将按预期开始。假设我现在离开 MyComponent,并且 MyComponent 现在应该被销毁。但我仍然可以看到订阅仍然存在(控制台日志不断出现)。在主机组件 (MyComponent) 被销毁后允许订阅继续存在有什么实际好处?
(如果我想取消订阅,可以在MyComponent的ngOnDestroy()方法中进行,但如何取消订阅不是这里讨论的重点)
Sha*_*vek -1
这observable
是 RxJS 的一个概念,独立于Angular
生命周期。
截至目前,stream of data
您订阅的 是独立于 Angular 生命周期进行订阅和监控的。因此,即使被component
销毁,内存也会保留引用,因此我们会出现内存泄漏。
因此,我们需要明确地告诉 ,通过同相RxJS
删除该引用。unsubscribing
observable
destroy
归档时间: |
|
查看次数: |
1555 次 |
最近记录: |