当只有 1 个 http 请求时,Angular HttpClient 发出多个 http 请求

标签 angular

我只期待一个 http 请求,但在我的控制台中我收到多个 http 调用。我不完全确定原因。为了便于阅读,下面是缩写。

组件.html

{{ (user | async).firstname }}  {{ (user | async).firstname }}

<ul>
  <li *ngFor="let profile of (user | async)?.profiles "> 
    <div>
        <p>{{ profile.profileType }}<span *ngIf="isStudent(profile.specialized)"> - {{ profile.specialized }}</span></p>
        <p>{{ profile.id }}</p>
    </div>

    <button class="btn btn-primary float-right" (click)="onGo(profile)">Go</button>
  </li>
</ul>

组件.ts

private user: Observable<User>;

ngOnInit(){

   this.user = this.userDataService.fetchUserDetails(+params['id']);

}

用户数据服务.ts

fetchUserDetails(id:number):Observable<User> {
console.log("calls 1 ?"); // this only gets called once!!!
return this.httpClient.get<User>(this.apiUrl + "/" + id)
  .pipe(
    tap((response) => {

      console.log(response); // this is executed multiple times!!!


      return response;
    }),
    catchError( (error) => {
      handleIt();
    })
  )

在我的控制台中

enter image description here

在我的网络中

enter image description here

是什么让 HttpClient 发出如此多的 http 请求?当 UserDataService 显然只被执行一次时......

最佳答案

每个异步管道都会创建自己的可观察对象订阅,并以单独的 API 调用结束。你有两种选择来解决它。

选项 1: 使用 as 运算符来保存结果,如下所示:

<ng-container *ngIf="user | async as u">
 {{ u.firstname }}
 ...
</ng-container>

选项 2: 使用 rxjs 的共享运算符:

return this.httpClient.get<User>(this.apiUrl + "/" + id)   .pipe(
  tap(console.log), // this is executed multiple times!!!
    share(),
    catchError( (error) => {
      handleIt();
    })
);

关于当只有 1 个 http 请求时,Angular HttpClient 发出多个 http 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50983867/

相关文章:

在组件中使用模型的 Angular 2 错误

angular - 如何模拟包含 http 请求并返回 observable 的服务?

css - Angular Bootstrap 中不存在 pull-right

html - 如何设置页面上最后一个 Angular 组件的样式?

html - 如何创建管道以突出显示具有给定单词列表的句子中的文本

angular - 显示 Angular react 表单错误消息的最佳方式,一个表单控制多个验证错误?

javascript - 无法读取未定义的属性 'post' - Angular 2

angular - Angular2中圆括号、括号和星号有什么区别?

angular - NullInjectorError : No provider for InjectionToken MatDialogData

javascript - 拖放 CDK : keep showing dragged element inside starting list