ngFor块内的模板中的异步管道会触发http GET调用循环 [英] Async Pipe in Template inside ngFor block triggers http GET calls loop

查看:160
本文介绍了ngFor块内的模板中的异步管道会触发http GET调用循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下组件模板:

<div *ngFor="let ctrl of data; trackBy:ctrl?.Id">
   <div *ngIf="getNext(ctrl.nextDate) | async as next">
        <span>{{next | date: 'dd.MM.yyyy'}}</span>
   </div>
</div>

getNext()是返回Observable<Date>的简单方法:

getNext() is a simple method returning an Observable<Date>:

public getNext(deadline: string): Observable<Date> {
   return this.http.get<Date>(`${this.config.apiEndpoint}/api/meeting?deadline=${deadline}`);
}

我的目标是调用方法并使用模板中的异步管道订阅可观察对象.但是,当我运行应用程序时,会生成无数的GET和OPTIONS请求.

My goal would be to invoke the method and subscribe to the observable with the async pipe in the template. However when I run the application endless GET and OPTIONS requests are generated.

如果将方法调用放在ng之外,也会发生同样的情况.该调用将需要在ngFor内部执行,因为每个收集项的参数都不同.

Also if I place the method call outside the ngFor the same happen. The call would need to be executed inside the ngFor as the parameter is different for each collection item.

为什么只调用一次该方法,订阅后就不再产生调用?

Why the method is simply called once and no more calls generated after the subscription?

推荐答案

在模板中调用函数通常不是一个好主意,因为它会导致不可预测的结果.这样可以重组代码来避免这种情况:

Calling functions in template is usually not a very good idea as it leads to unpredictable results. This is how you can restructure your code to avoid this:

data: any = [....] // some data
data$: Observable[];

ngOnInit() {
    this.data$ = this.data.map(elem => this.getNext(elem));
} 

public getNext(deadline: string): Observable<Date> {
   return this.http.get<Date>(`${this.config.apiEndpoint}/api/meeting?deadline=${deadline}`);
}

在您的模板中:

<div *ngFor="let ctrl of data$">
   <div *ngIf="ctrl | async as next">
        <span>{{next | date: 'dd.MM.yyyy'}}</span>
   </div>
</div>

这是我创建的Stackblitz,您可以在其中查看类似机制的工作原理: https://stackblitz.com /edit/angular-nyn4qz

Here's a stackblitz I created where you can see how a similar mechanism works: https://stackblitz.com/edit/angular-nyn4qz

这篇关于ngFor块内的模板中的异步管道会触发http GET调用循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆