我只期待一个 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();
})
)
在我的控制台中
在我的网络中
是什么让 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/