Infinite loop with store and http with ngFor

淺唱寂寞╮ 提交于 2019-12-06 13:16:46

问题


I have infinite loop with this code: Template:

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

Service:

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)))
}

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


回答1:


It's not actually an infinite loop.

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();
} 

and

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


来源:https://stackoverflow.com/questions/46598472/infinite-loop-with-store-and-http-with-ngfor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!