Reputation: 434
I have an angular app where i want to first fetch a bunch of parent elements and then for each parent the corresponding children (1 parent to n children).
I currently fetch the parents by async-piping an observable. Up to this point everything seems to be ok.
Then I call a Function that should get me the corresponding children per parent. But then the Application goes berserk. The program send several HttpRequest and it seems like it is trying to refetch the children all the time. I cannot figure out what exactly is causing it, but I already assume it has something to do with the update-detection. But because parent$-Observable only gets updated once(when the http request finishes) I do not really know what else there could be that creates this loop of continuous reload.
getChild$() is a method that returns an observable from a http-request parent$ is an observable that only updates once in a runtime (request finishes)
<div *ngFor="let parent of parent$ | async">
{{parent?.name}}
<div *ngFor="let child of getChild$(parent.id) | async">
{{child?.name}}
</div>
</div>
Upvotes: 1
Views: 318
Reputation: 24424
getChild
method will run in every angular change detection cycle so any change will trigger run the method because angular can't know if the value has change or not ,
one way to solve this by create a pipe that gone to handle create the observable then chain this with the async pipe
import { Pipe, PipeTransform } from '@angular/core';
import {HttpClient} from "@angular/common/http"
@Pipe({
name: 'getChild'
})
export class GetChildPipe implements PipeTransform {
constructor(private http:HttpClient){}
transform(id: any,): any {
const url = `http://api.something.com/${id}`
return this.http.get(url);
}
}
template
<div *ngFor="let parent of parent$ | async">
{{parent?.name}}
<div *ngFor="let child of parent.id | getChild | async">
{{child?.name}}
</div>
</div>
check this 👉 function gets called several times
Upvotes: 4