带store的无限循环和带ngFor的http [英] Infinite loop with store and http with ngFor

查看:54
本文介绍了带store的无限循环和带ngFor的http的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码的无限循环: 模板:

I have infinite loop with this code: Template:

<ng-container *ngFor="let row of service.dataLoadAsync() | async">

服务:

dataLoadAsync(filters: FinishedCallsFilter = {}): Observable<FinishedCall[]> {
    return this.httpFinishedCallsObservable(Object.assign({limit: this.limit}, {})).flatMap(response => {
        this.store.dispatch(new ReplaceMany(response.items))
        return this.store
    })
}

我也尝试了此功能的实现:

Also I tried this function realization:

dataLoadAsync(filters: FinishedCallsFilter = {}): Observable<FinishedCall[]> {
   this.httpFinishedCallsObservable(Object.assign({limit: this.limit}, {}))
        .subscribe(response => this.store.dispatch(new ReplaceMany(response.items)))
    return this.store
}

private httpFinishedCallsObservable(params: { limit: number, tag ?: string }) {
    return this.http.post(this.apiUrl, params)
        .map((json) => this.parseHttp(json))
        .do(response => this.tagStore.dispatch(new UpdateTag(response.tag)))
}

所以,问题出在这里.如果没有http请求,则evferything很好.但是随后我尝试下载数据并更新存储,dataLoadAsync函数在循环中多次调用. 如何修复代码?我想将存储用于缓存

So, the problem. Without http request, evferything is fine. But then I try to download data and update store, dataLoadAsync function calls a lot of times in loop. How to fix the code? I want to use store for cache

推荐答案

它实际上不是无限循环.

It's not actually an infinite loop.

如果将功能绑定到模板中,则每次运行Angular变化检测时都会调用该功能.

If you bind a function in the template, the function is called every time Angular change detection runs.

通常,这是一种不好的做法.而是将结果分配给一个字段并绑定到该字段.

This is bad practice in general. Instead assign the result to a field and bind to that field instead.

constructor() {
  this.data = service.dataLoadAsync();
} 

<ng-container *ngFor="let row of service.data | async">

这篇关于带store的无限循环和带ngFor的http的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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