Riyad
Riyad

Reputation: 377

How to use Angular-6 HttpClient method in a for-loop

I am trying to iterate one of my HTTP get() call. It doesn't work properly. I don't know in Angular 6 how can work HTTP method in for loop. Another issue is that If I omit the for loop then the rxjs delay() function doesn't work.

getRoleOftheUser() {

   for ( let i = 0; i < this.arr.length; i++) {
       return  this.http.get<any>(`${this.baseURL}/aaa/groups/${this.arr[i]}/effectiveRolesByUser`)
        .pipe(map(res => res) , delay(5000) ).subscribe(result => console.log(result));
        }
    }

This is not an asynchronous javaScript issue. It's all about rxjs looping. Does anyone please guide me how I can iterate HTTP call in for loop in Angular 6? Thanks

Upvotes: 0

Views: 1950

Answers (1)

Trash Can
Trash Can

Reputation: 6824

Why not taking advantage of rxjs' power? Something like this

import { of } from 'rxjs';
import { concatMap, delay } from 'rxjs/operators';

.
.
.
getRoleOftheUser() {
  if (this.arr.length > 0)
    of(...this.arr)
      .pipe(
        concatMap(item => this.http.get<any>(`${this.baseURL}/aaa/groups/${item}/effectiveRolesByUser`)),
        delay(5000)
      )
      .subscribe(result => console.log(result));
}
.
.
.

Upvotes: 1

Related Questions