Angular 是否清除 属性 或 ngOnDestroy 上的数组以防止内存泄漏?
Does Angular clear property or array on ngOnDestroy to prevent memory leak?
我有以下代码:(Angular 9)
employee.component.ts
name:string;
arr = [];
ngOnInit() {
this.name = "abc";
for (let i = 0; i < 1000; i++) {
this.arr.push(i);
}
}
Now when I move to another component using angular routing, then
component named employee will be destroyed.
所以我是否需要像下面这样在 ngOnDestroy() 方法上清除数组和名称 属性 以防止内存泄漏?
ngOnDestroy() {
this.name = "";
this.arr = [];
}
或 angular 将清除 ngOnDestroy 上的数组和属性?
您不需要,因为这些变量将被垃圾回收 https://angular.io/guide/lifecycle-hooks#ondestroy
您不需要,垃圾收集器会处理。只需确保您的组件没有订阅任何可观察对象等。如果 subscription/component 仍然有一些指向根的引用,它将不会被垃圾收集。
要处理订阅,您应该使用 ngOnDestroy
取消订阅所有订阅。下面是一个例子:
@Component({...})
export class AppComponent implements OnInit, OnDestroy {
subscriptions: Subscription[] = [];
ngOnInit () {
var observable = Rx.Observable.interval(1000);
var observable2 = Rx.Observable.interval(1000);
this.subscriptions.push(observable.subscribe(x => console.log(x)));
this.subscriptions.push(observable2.subscribe(x => console.log(x)));
}
ngOnDestroy() {
this.subscriptions.forEach((subscription) => subscription.unsubscribe())
}
}
我有以下代码:(Angular 9)
employee.component.ts
name:string;
arr = [];
ngOnInit() {
this.name = "abc";
for (let i = 0; i < 1000; i++) {
this.arr.push(i);
}
}
Now when I move to another component using angular routing, then component named employee will be destroyed.
所以我是否需要像下面这样在 ngOnDestroy() 方法上清除数组和名称 属性 以防止内存泄漏?
ngOnDestroy() {
this.name = "";
this.arr = [];
}
或 angular 将清除 ngOnDestroy 上的数组和属性?
您不需要,因为这些变量将被垃圾回收 https://angular.io/guide/lifecycle-hooks#ondestroy
您不需要,垃圾收集器会处理。只需确保您的组件没有订阅任何可观察对象等。如果 subscription/component 仍然有一些指向根的引用,它将不会被垃圾收集。
要处理订阅,您应该使用 ngOnDestroy
取消订阅所有订阅。下面是一个例子:
@Component({...})
export class AppComponent implements OnInit, OnDestroy {
subscriptions: Subscription[] = [];
ngOnInit () {
var observable = Rx.Observable.interval(1000);
var observable2 = Rx.Observable.interval(1000);
this.subscriptions.push(observable.subscribe(x => console.log(x)));
this.subscriptions.push(observable2.subscribe(x => console.log(x)));
}
ngOnDestroy() {
this.subscriptions.forEach((subscription) => subscription.unsubscribe())
}
}