Sunny Srivastava
Sunny Srivastava

Reputation: 189

How to make multiple http subscribe inside a loop in Angular?

I am stuck in a situation where I have to loop through an array of strings that are passed to service as a parameter which gives a response through the HTTP subscribe method. And some operations were made with a response.

But the issue is, the subscribe event skips the operations and moves to the next string in the loop, which in turn returns undefined.

My TS looks like -

ngOnInit() {

this.locString.push('57b17265-2629-4ca9-ac1f-d20d59544343');
this.locString.push('cefead77-b413-43c9-9ba8-d917a0e56a7b');
this.locString.push('58d39891-cae2-4818-838f-162426030132');

}

show(){
    var userList = ''
    for(var str of this.locString){
        this.tableService.getDataWithParams(str).subscribe(res=>{
          for(var abc of res){
            userList+= abc.Username + ',';
          }
        });
      }
      console.log(userList);
    }

}

The API call returns the value as -

[{"Id":1,"Username":"Hull","City":"Cleary","Country":"Seychelles"},{"Id":1,"Username":"Palmer","City":"Tuskahoma","Country":"Niger"},{"Id":1,"Username":"Brennan","City":"Sanborn","Country":"Bosnia and Herzegovina"},{"Id":1,"Username":"Gill","City":"Logan","Country":"French Guiana"},{"Id":1,"Username":"Sloan","City":"Neibert","Country":"Australia"}]

My expected O/P is all the usernames for every result formed by the locString array -

Hull, Palmer, Brennan, Gill, Sloan, .....( and so on for all strings in the array locString )

Have created a StackBlitz link for the same. Please help. TIA

Upvotes: 1

Views: 1433

Answers (1)

Eliseo
Eliseo

Reputation: 57981

some like

forkJoin(this.locString.map(str=>this.tableService.getDataWithParams(str)))
.subscribe((res:any[])=>{
      console.log(res)
    })

give us an array of three elements each element is another array

As we only want the unique names of the response we can make a forkJoin only with the response of the names

 forkJoin(this.locString.map(str=>this.tableService.getDataWithParams(str).pipe(
      map((res:any[])=>{
      return res.map(x=>x.Username)
    }))))
 .subscribe((res:any[])=>{
          console.log(res)
        })

As we want the uinque values we can use reduce

forkJoin(this.locString.map(str=>this.tableService.getDataWithParams(str).pipe(map((res:any[])=>{
  return res.map(x=>x.Username)
}))))
.pipe(map((res:any[])=>res.reduce((a:string[],b:string[])=>
  [...a,...b.filter(x=>a.indexOf(x)<0)]
,[]))
).subscribe((res:any[])=>{
  console.log(res)
})

Upvotes: 1

Related Questions