Angular 我应该销毁什么?我该怎么做?

Angular 我应该销毁什么?我该怎么做?,angular,lifecycle,Angular,Lifecycle,我查看了angular文档和其他资源,但什么也没找到。 我在Angular7上工作。如何执行销毁过程?从'@angular/core'导入{Component,OnDestroy}; @组件({…}) 导出类MyComponent实现OnDestroy{ ngOnDestroy():void{ //当组件被销毁时调用 } } 您可以在此处阅读有关生命周期的更多信息:取消订阅组件中所有可见项的干净方法: //declare private ngUnsubscribe: Subject<a

我查看了angular文档和其他资源,但什么也没找到。 我在Angular7上工作。如何执行销毁过程?

从'@angular/core'导入{Component,OnDestroy};
@组件({…})
导出类MyComponent实现OnDestroy{
ngOnDestroy():void{
//当组件被销毁时调用
}
}

您可以在此处阅读有关生命周期的更多信息:

取消订阅组件中所有可见项的干净方法:

//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();
    }
//声明
private ngUnsubscribe:Subject=new Subject();
//在订阅观测值的位置添加takeUntill
this.myService.serviceFunction()
.pipe(takeUntil(this.ngUnsubscribe))
.订阅(
res=>{
//使用res
},
错误=>{}
);
//全部退订
恩贡德斯特罗(){
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}

我认为您的问题不是如何执行销毁过程,而是在该过程中要做什么。嗯,90%的时候你不需要Ngondestory,但是如果你订阅了一个observable,或者你正在使用事件循环(例如,使用超时),那就是说“我要走了,我不会使用你的响应!”的最好地方,你可以取消订阅。你不需要销毁变量,垃圾收集器会帮你做的!
//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();
    }