我只期待一个 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>
Run Code Online (Sandbox Code Playgroud)
组件.ts
private user: Observable<User>;
ngOnInit(){
this.user = this.userDataService.fetchUserDetails(+params['id']);
}
Run Code Online (Sandbox Code Playgroud)
用户数据服务.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();
})
)
Run Code Online (Sandbox Code Playgroud)
}
在我的控制台
在我的网络
是什么让 HttpClient 发出如此多的 http 请求?当 UserDataService 明确只执行一次时......
每个异步管道都会创建自己对可观察对象的订阅,最终以单独的 API 调用结束。您有两种选择来解决它。
选项 1: 使用 as 运算符保存结果,如下所示:
<ng-container *ngIf="user | async as u">
{{ u.firstname }}
...
</ng-container>
Run Code Online (Sandbox Code Playgroud)
选项 2: 使用 rxjs 中的共享运算符:
return this.httpClient.get<User>(this.apiUrl + "/" + id) .pipe(
tap(console.log), // this is executed multiple times!!!
share(),
catchError( (error) => {
handleIt();
})
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1619 次 |
| 最近记录: |