问题
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