So I have a method that get tree parents by id from the server
getParentById(id:string):return httpClient
I want to loop over this method and take the parentId returned from this call and put it back as a parameter to get the children, I only have the very first parentId so i pass it in the first call;
this.parentId ='123'
for(let i =0;i<arr.length;i ){
this.getNodeById(this.parentId).subscribe(res =>{
this.parentId = res.parentId;
// I am trying to append the parent id I have, so in the next iteration of th loop, the
parent id is updated
})
}
The problem is that the very first parentId value is not changing and all the requests are sent with the same parentId ,How can I solve this issue ?
CodePudding user response:
The problem is most likely that you are subscribing to this function:
this.getNodeById(this.parentId)
x arr.length
times really fast.
And only then your values arrive, all for the same id.
CodePudding user response:
The best solution for you is to use EXPAND, an rxjs operator for recursive calls
import { from, EMPTY } from 'rxjs';
import { expand, tap} from 'rxjs/operators';
this.getNodeById(this.parentId).pipe(
tap(res => {
// do something on success
}),
expand((res) => res.parentId // call getNodeById if you have a parentId otherwise return EMPTY
? this.getNodeById(res.parentId)
: EMPTY;
)
).subscribe(console.log)