Angular HttpClient退订

问题描述 投票:0回答:3

是否需要从Angular Observable的方法返回的HttpClient退订?

例如:

this.http.get(url).subscribe(x => this.doSomething());

我需要取消订阅此订阅吗?我问这是因为我不知道Angular是否自行处理。另外,请求是一次性的,不是连续的。我倾向于认为我不需要。您有什么想法?

根据以下信息:Angular/RxJs When should I unsubscribe from `Subscription`

RxJS处理一次性订阅,但我没有在他们的文档中找到任何内容。

angular rxjs observable
3个回答
0
投票

有两种处理方法:

1)是,如果您在ts文件中正常订阅了可观察节目,则必须手动退订。通常我们可以在ngOnDestroy()生命周期方法中取消订阅]

2)如果您在角度模板中的observable上使用异步管道语法,那么它将自动关闭订阅

observable | async 

请参阅以下内容:https://angular.io/api/common/AsyncPipe


0
投票

是,必须根据https://blog.angularindepth.com/the-best-way-to-unsubscribe-rxjs-observable-in-the-angular-applications-d8f9aa42f6a0取消订阅

这是我的工作:


export class CustomerSummaryComponent implements OnInit, OnDestroy {
  subscriptions: Subscription[];

  ngOnInit() {
    this.subscriptions = [];

    this.subscriptions.push(
        this.customerService.getCustomer(this.customerId).subscribe(
        data => {
        },
        error => {
            console.log(error);
        }
        )
    );
  }

  ngOnDestroy() {
    for (const x of this.subscriptions) {
      x.unsubscribe();
    }
  }
}


0
投票

不,您不需要取消订阅。观察直到得到api的响应。一旦Http请求完成,它就会自动退订。

参考此

Why not to unsubscribe Http Observables

Angular guide http

AsyncPipe

© www.soinside.com 2019 - 2024. All rights reserved.