0

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 ?

  • thank you for the explanation, I am new to coding so I just talk about what I am using, anyways, Is there a common work around to handle this situations? – Ziad Mohamed Oct 22 '21 at 23:32

2 Answers2

3

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)
Fateh Mohamed
  • 20,445
  • 5
  • 43
  • 52
2

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.

H3AR7B3A7
  • 4,366
  • 2
  • 14
  • 37
  • so how can I make it work , for example is there a method to make the next request executed if just the current request got it's res ? – Ziad Mohamed Oct 22 '21 at 23:26
  • Take a look at [this question](https://stackoverflow.com/questions/24586110/resolve-promises-one-after-another-i-e-in-sequence). – H3AR7B3A7 Oct 22 '21 at 23:32