重新订阅时出现Angular ObjectUnsubscribedError

Or *_*cov 4 subscribe eventemitter angular

在调用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();
  }
Run Code Online (Sandbox Code Playgroud)

core.js:1601错误错误:EventEmitter.push ../ node_modules / rxjs / _esm5 / internal / Subject.js.Subject._trySubscribe(Subject.js:86)处的新ObjectUnsubscribedError(ObjectUnsubscribedError.js:6)上的对象已取消订阅EventEmitter.push ../ node_modules / rxjs / _esm5 / internal / Observable.js.Observable.subscribe(Observable.js:28)位于EventEmitter.push。在EcoProcedureFormComponent.push ../ src / app / forms / eco-form / eco-procedure-form.component.ts.EcoProcedureFormComponent.ngOnInit(eco-procedure-form.component.ts:57)上订阅(core.js:3743) )在对象的prodCheckAndUpdateNode(core.js:11333)的checkAndUpdateNode(core.js:11333)的checkAndUpdateNodeInline(core.js:11371)的checkAndUpdateDirectiveInline(core.js:10105)处。评估[作为updateDirectives](EcoProcedureFormComponent_Host.ngfactory.js:10)

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

我该如何解决?

谢谢

dAx*_*xx_ 6

您应该添加一个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();
    }
  }
Run Code Online (Sandbox Code Playgroud)

如果要取消订阅,可以使用.add()将“子级”添加到订阅中,然后可以取消订阅。如果您需要更多的动态控制,只需为每个变量添加变量(甚至将它们拆分为组),以便您拥有更多的控制权。

  • 它有效,但我很好奇,为什么使用订阅变量可以消除错误? (4认同)