Angular 重新订阅时出现 ObjectUnsubscribedError

Angular ObjectUnsubscribedError while resubscribe

在调用 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 ERROR Error: object unsubscribed at new ObjectUnsubscribedError (ObjectUnsubscribedError.js:6) at EventEmitter.push../node_modules/rxjs/_esm5/internal/Subject.js.Subject._trySubscribe (Subject.js:86) at EventEmitter.push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe (Observable.js:28) at EventEmitter.push../node_modules/@angular/core/fesm5/core.js.EventEmitter.subscribe (core.js:3743) at EcoProcedureFormComponent.push../src/app/forms/eco-form/eco-procedure-form.component.ts.EcoProcedureFormComponent.ngOnInit (eco-procedure-form.component.ts:57) at checkAndUpdateDirectiveInline (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 变量并将订阅的 return 值分配给它。然后在 ngOnDestroy 方法中,您应该通过调用它的 unsubscribe 方法来释放订阅。

示例:

private routesSubscription: Subscription;
private 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()在订阅中添加“children”。然后,您可以一次取消订阅所有订阅。如果您需要更多控制,只需为每个变量添加变量(甚至将它们分成组)。

-- 更新--

其他解决方案的示例:

示例 1:

subscriptions = new Subscription();

someFunc = () => {
    this.subscriptions.add(
        something.subscribe();
    );
}

ngOnDestroy(){
    if(this.subscriptions){
        this.subscriptions.unsubscribe();
    }
}

示例 2:

subscriptionGroup: Subscription[]= [];

someFunc = () => {
    this.subscriptionGroup.push(something.subscribe())
}

someOtherFunc = () => {
    this.subscriptionGroup.push(somethingElse.subscribe())
}

ngOnDestroy(){
    this.subscriptionGroup.forEach(subscription => {
        subscription.unsubscribe()
    }
}