在尝试在调用ngOnDestroy并调用unsubscribe后第二次订阅EventEmitter时,我收到以下错误:
ngOnInit() {
this.route.params.subscribe(params => {
this.resources.eco_id= params['id']
});
this.http.ReloadForm.subscribe(res=>this.OnFormLoad(res));
}
ngOnDestroy(){
this.http.ReloadForm.unsubscribe();
}
core.js:1601 ERROR错误:在EventEmitter.push ../ node_modules / rxjs / _esm5 / internal / Subject.js.Subject._trySubscribe(Subject.js:86)at at new ObjectUnsubscribedError(ObjectUnsubscribedError.js:6)处取消订阅EventEmitter.push ../ node_modules / rxjs / _esm5 / internal / Observable.js.Observable.subscribe(Observable.js:28)在EventEmitter.push ../ node_modules/@angular/core/fesm5/core.js.EventEmitter。订阅(core.js:3743)在EcoProcedureFormComponent.push ../ src / app / forms / eco-form / eco-procedure-form.component.ts.EcoProcedureFormComponent.ngOnInit(eco-procedure-form.component.ts:57 )checkAndUpdateNireInline(core.js:10105)at checkAndUpdateNodeInline(core.js:11371)at checkAndUpdateNode(core.js:11333)at prodCheckAndUpdateNode(core.js:11877)at object.eval [as updateDirectives](EcoProcedureFormComponent_Host.ngfactory。 JS:10)
没有取消订阅ngOnDestroy一切正常,但我必须发布订阅一些如何。
我该如何解决?
谢谢
您应该添加一个Subscription变量,并为其分配订阅,然后在ngOnDestroy中通过取消订阅该变量来释放订阅。 类似的东西:
routesSubscription: Subscription;
serviceSubscription: Subscription;
ngOnInit() {
this.routesSubscription= this.route.params.subscribe(params => {
this.resources.eco_id= params['id']
});
this.serviceSubscription= this.http.ReloadForm.subscribe(res=>this.OnFormLoad(res));
}
ngOnDestroy(){
if(this.routesSubscription){
this.routesSubscription.unsubscribe();
}
if(this.serviceSubscription){
this.serviceSubscription.unsubscribe();
}
}
如果您想要取消订阅,可以使用.add()将“孩子”添加到订阅中,然后您可以一起取消订阅。如果您需要更多动态控件,只需为每个控件添加变量(甚至将它们拆分为组),这样您就可以获得更多控制权。