Angular:每次我需要更新时,我应该订阅()到http.get()吗?

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

我想知道我是否使用了Observable.subscribe()太多次了。

在我的组件类中,我有一个函数loadData()。它调用另一个函数this.service.getData(),该函数使用HttpClient.get()来执行对服务器的HTTP请求。

目前在我的函数loadData()中,我订阅了this.service.getData()的结果。

每次用户点击“更新”按钮时,我想调用我的函数loadData()。

The question

  • 如果每次我需要执行HTTP请求时都调用我的函数loadData(),我会创建尽可能多的订阅者吗?
  • 是否存在内存泄漏的风险?
  • 如果是这样,你知道我应该如何重构我的代码吗?

The answer

Samples of code

private loadData() {
    this.loading = true;
     const subscription = this.service.getData()
      .pipe(
  // console.log() with a delay added for test - START
  map(val => {
    window.setTimeout(() => {
      // This will print true.
      console.log('After delay: Is Subscriber closed?', subscription.closed);
    }, 10);
    return val;
  }),
    // console.log() with a delay added for test - END
    takeUntil(this.ngUnsubscribe))
      .subscribe(data => {
        this.data = data;
        // This will print false.
        console.log('Is Subscriber closed?', subscription.closed);
      },
      error => {
        console.error(error);
        throw error;
      },
      () => {
        this.loading = false;
      });
}
getData(): Observable<DataObject> {
    const uri = encodeURI(this.configService.getUri());
    const headers = new HttpHeaders();
    if (this.pipelineEtag) {
      headers.set('If-None-Match', this.pipelineEtag);
    }
    return this.http.get(uri, {
      headers: headers,
      observe: 'response'
    }).pipe(
      map(resp => this.processResponse(resp)),
      catchError(error => this.handleError(error, this.envProduction))
    );
}
angular observable subscribe
3个回答
0
投票

每次HTTP调用返回一个值时,Observable都会完成。所以在服务中做这样的事情是安全的

loadData() { 

    return this.http.get<Data>(dataUrl).pipe(
      //  tap(data => console.log(data)), // eyeball results in the console
      catchError(err => this.handleError(err))
    );

}

然后打电话

this.service.loadData().subscribe((data:Data) => do somthing)

你甚至可以调用exhaustMap或switchMap来控制Observable流,以免“提示”太多时间服务器


0
投票

这是正确的用法,创建多个订阅者没有风险。

从文档:

AsyncPipe会自动为您订阅(和取消订阅)。

Source


技术细节是,一旦Http请求完成,就会调用observable的.complete方法,该方法会杀死所有当前用户。这意味着您的订户已创建,使用,并立即被丢弃。


0
投票

所以最后

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