我应该在 angular 销毁什么?我该怎么办?
What should I destroy on angular? How should I?
我查看了 angular 文档和其他资源,但没有找到任何内容。
我在 Angular7 上工作。如何进行销毁处理?
import { Component, OnDestroy } from '@angular/core';
@Component({...})
export class MyComponent implements OnDestroy {
ngOnDestroy(): void {
// called when the component gets destroyed
}
}
您可以在此处阅读有关生命周期的更多信息:https://angular.io/guide/lifecycle-hooks
See this scenario
import { Subscription } from 'rxjs';
currentUserSub: Subscription;
getCurrentUser() {
this.currentUserSub = this.authenticationService.currentUser.subscribe(x => {
if (x) {
this.currentUser = x[0].MemberId;
} else { }
});
ngOnDestroy() {
// unsubscribe to ensure no memory leaks
this.currentUserSub.unsubscribe();
}
}
取消订阅组件中所有可观察对象的简洁方法:
//declare
private ngUnsubscribe: Subject<any> = new Subject<any>();
//add takeUntill where subscribing to observables
this.myService.serviceFunction()
.pipe(takeUntil(this.ngUnsubscribe))
.subscribe(
res => {
// use res
},
err => {}
);
//unsubscribe all
ngOnDestroy() {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
我查看了 angular 文档和其他资源,但没有找到任何内容。 我在 Angular7 上工作。如何进行销毁处理?
import { Component, OnDestroy } from '@angular/core';
@Component({...})
export class MyComponent implements OnDestroy {
ngOnDestroy(): void {
// called when the component gets destroyed
}
}
您可以在此处阅读有关生命周期的更多信息:https://angular.io/guide/lifecycle-hooks
See this scenario
import { Subscription } from 'rxjs';
currentUserSub: Subscription;
getCurrentUser() {
this.currentUserSub = this.authenticationService.currentUser.subscribe(x => {
if (x) {
this.currentUser = x[0].MemberId;
} else { }
});
ngOnDestroy() {
// unsubscribe to ensure no memory leaks
this.currentUserSub.unsubscribe();
}
}
取消订阅组件中所有可观察对象的简洁方法:
//declare
private ngUnsubscribe: Subject<any> = new Subject<any>();
//add takeUntill where subscribing to observables
this.myService.serviceFunction()
.pipe(takeUntil(this.ngUnsubscribe))
.subscribe(
res => {
// use res
},
err => {}
);
//unsubscribe all
ngOnDestroy() {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}