重新订阅时出现Angular ObjectUnsubscribedError

时间:2018-08-04 13:36:59

标签: angular eventemitter subscribe

在调用ngOnDestroy并取消订阅后,第二次尝试订阅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错误错误:对象未订阅       在新的ObjectUnsubscribedError(ObjectUnsubscribedError.js:6)       在EventEmitter.push ../ node_modules / rxjs / _esm5 / internal / Subject.js.Subject._trySubscribe中   (Subject.js:86)       在EventEmitter.push ../ node_modules / rxjs / _esm5 / internal / Observable.js.Observable.subscribe   (Observable.js:28)       在EventEmitter.push ../ node_modules/@angular/core/fesm5/core.js.EventEmitter.subscribe中   (core.js:3743)       在EcoProcedureFormComponent.push ../ src / app / forms / eco-form / eco-procedure-form.component.ts.EcoProcedureFormComponent.ngOnInit   (eco-procedure-form.component.ts:57)       在checkAndUpdateDirectiveInline(core.js:10105)       在checkAndUpdateNodeInline(core.js:11371)       在checkAndUpdateNode(core.js:11333)       在prodCheckAndUpdateNode(core.js:11877)       在Object.eval [作为updateDirectives](EcoProcedureFormComponent_Host.ngfactory.js:10)

在ngOnDestroy上没有取消订阅的情况下,一切正常,但是我必须以某种方式释放订阅。

我该如何解决?

谢谢

1 个答案:

答案 0 :(得分:3)

您应该添加一个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()将“子级”添加到订阅中,然后可以退订所有。如果您需要更多的动态控制功能,只需为每个变量添加变量(甚至将它们分成几组即可),以便您有更多的控制权。

相关问题