Angular HttpClient退订

时间:2019-10-18 03:18:37

标签: angular rxjs observable

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

例如:

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

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

根据以下帖子: Angular/RxJs When should I unsubscribe from `Subscription`

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

4 个答案:

答案 0 :(得分:0)

有两种处理方法:

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

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

observable | async 

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

答案 1 :(得分:0)

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

请参阅

Why not to unsubscribe Http Observables

Angular guide http

AsyncPipe

答案 2 :(得分: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();
    }
  }
}

答案 3 :(得分:0)

当您使用ngOnDestroy离开页面时,可以在“相同”时间取消订阅页面中的所有Observable。您通过管道传递一个Observable,该Observable在离开页面并关闭功能时会被激活。

export class X implements OnInit, OnDestroy {
  private unsubscribe$ = new Subject();

  ngOnInit() {
    this.functionOne();
  }

  ngOnDestroy() {
    this.unsubscribe$.next();
    this.unsubscribe$.complete();
  }

  functionOne() {
    this.service
      .getData()
      .pipe(takeUntil(this.unsubscribe$))
      .subscribe(
        (result) => {},
        (error) => {}
      );    
  }
}

相关问题