【发布时间】:2021-03-16 14:39:51
【问题描述】:
我正在使用 Angular v11.0.2 做一个 Web 应用程序。我需要进行 HTTP 调用以在屏幕上显示一些信息。为了节省时间并利用 async 管道的好处,我在模板中使用它,但是它会导致多个请求永不停止。
服务
export class MyDataService {
constructor(
private http: HttpClient,
) {
}
fetchMyEmployeeData(): Observable<any[]> {
return this.http.post<any[]>('ENDPOINT', {});
}
}
组件
export class MyAwesomeComponent {
constructor(
public myDataService: MyDataService,
) {
}
}
模板
<ng-container *ngIf="(myDataService.fetchMyEmployeeData() | async) as data">
</ng-container>
这会导致多次请求并且永远不会停止。
如果我使用*ngFor,也会发生同样的情况:
<tr *ngFor="let d of (myDataService.fetchMyEmployeeData() | async)">
<td>.</td>
</tr>
我已经尝试了以下这个:
使用shareReplay 运算符:
fetchMyEmployeeData(): Observable<any[]> {
return this.http.post<any[]>('ENDPOINT', {}).pipe(shareReplay());
}
使用简单的 div:
<div *ngIf="(myDataService.fetchMyEmployeeData() | async) as data">
</div>
我知道如果我从组件订阅并将结果保存在局部变量中,我可以在模板中调用它,但这不是我的目标。工作示例:
export class MyAwesomeComponent implements OnInit {
data: any[];
constructor(
public myDataService: MyDataService
) {
}
ngOnInit() {
// This is not my goal because I will need to handle the subscription life manually.
this.myDataService.fetchMyEmployeeData().subscribe(res => this.data = res);
}
}
我也遵循了这里给出的建议:
- Multiple identical async pipe in Angular causing multiple http requests
- How can I prevent the Angular async pipe from making frequent server calls when no results come back?
我不知道究竟是什么导致了这个多次请求以及如何避免它。
我的目标是在模板中使用async 管道并只进行一次HTTP 调用。
【问题讨论】:
-
想象一下,您在 ts 文件中编写了类似
myDataService.fetchMyEmployeeData().subscribe(); myDataService.fetchMyEmployeeData().subscribe()的代码。尝试调试它。你会发现每个fetchMyEmployeeData()执行都会返回一个new Observable -
@yurzui 确实如此。所以你是说我正在尝试做的事情返回多个可观察对象,这就是为什么我看到多个请求?有道理,但现在我不明白其他人如何在没有这种行为的情况下在模板中使用
async管道。我的意思是,在模板中使用async的一个好处是避免处理组件中的订阅生命周期。还有一些教程展示了相同的技术,而无需尝试我的问题。你有什么建议吗?我很困惑。 -
在你的组件中将 observable 定义为像
employeeData$ = this.myDataService.fetchMyEmployeeData()这样的属性,你会对模板中的employeeData$ | async感到满意。 -
@andriishupta 如果我们需要在模板中使用两个异步管道,则需要它
-
我以为是ngContainer和ngFor指令的情况,没仔细看
标签: angular angular-httpclient