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

2024-04-16

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

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

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

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

问题

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

答案

  • 我发现了另一个帖子是否有必要取消订阅 Http 方法创建的 observables? https://stackoverflow.com/questions/35042929/is-it-necessary-to-unsubscribe-from-observables-created-by-http-methods
  • 它解释了 Angular 代码实际上在 HTTP 请求之后调用 observable.complete (),有延迟
  • 所以我修改了下面的代码来检查这一事实,测试证实这是真的

代码示例

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))
    );
}

每次 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流,以免“提示”服务器太多次

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular:每次需要更新时,我应该 subscribe() 到 http.get() 吗? 的相关文章

随机推荐