dany
dany

Reputation: 19

How to Wait the for loop in angular for the response?

How to wait the for loop in angular for the response? And update the latest value of the response.

users: Users

getUsers(){
    this.userService.getUsers().subscribe(
        (res: Users) => {
            this.users = res
        }
    )
}

setValue(){

    for (let i = 0; i < this.users.length; i++) {

        if (this.users.length > 0) {

            break
        }

        ///some code
        this.getUsers()
    }
}

Upvotes: 1

Views: 2629

Answers (1)

Yash Rami
Yash Rami

Reputation: 2327

If you want to call API inside your loop you can use async await here is the example.

async setValue() {
 for (let i = 0; i < this.users.length; i++) {
        if (this.users.length > 0) {
            break
        }
        ///some code
        await this.getUsers();
        console.log(i);  // here you can see that this line will execute after the api call is completed 
    }
}

getUsers(){
  return new Promise(resolve => {
      this.userService.getUsers().subscribe(
        (res: Users) => {
            this.users = res;
            resolve();
        }, err => {
            resolve();
        })
   }
 }

Upvotes: 2

Related Questions