首页 > 解决方案 > Angular:每次我需要更新时,我应该订阅()到 http.get()吗?

问题描述

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

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

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

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

问题

答案

代码示例

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

标签: angularobservablesubscribe

解决方案


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


推荐阅读