Skip to content Skip to sidebar Skip to footer

Wait For Asynchronous Functions To Finish In Angular

So I was working on a new component in Angular and in the ngOninit I have the following asynchronous functions below... This.getUserProfile needs to be finished before I can call t

Solution 1:

You can use basic promises with async/await.

async ngOnInit() {

    await this.getUserProfile(); // <-- 1. change// my-workplace depends on a private group and we need to fetch that group and edit// the group data before we proceed and get the group postif (this.isItMyWorkplace) {
      this.getPrivateGroup();
    }
    this.loadGroupPosts();
  }

async getUserProfile() {
    this._userService.getUser()
      .subscribe((res) => {
        this.user = res.user;
        console.log('log user', this.user);
        this.profileImage = res.user['profile_pic'];
        this.profileImage = this.BASE_URL + `/uploads/${this.profileImage}`;
        returntrue; // <-- this
      }, (err) => {
        this.alert.class = 'alert alert-danger';
        if (err.status === 401) {
          this.alert.message = err.error.message;
          setTimeout(() => {
            localStorage.clear();
            this._router.navigate(['']);
          }, 3000);
        } elseif (err.status) {
          this.alert.class = err.error.message;
        } else {
          this.alert.message = 'Error! either server is down or no internet connection';
        }
        throw err;
      });

}

Solution 2:

You could instead leverage RxJS and use a switchMap something like this (syntax NOT checked):

getData(): Observable<string[]> {
  returnthis._userService.getUser()
    .pipe(
      switchMap(userInfo=> {
         returnthis.getPrivateGroup();
      }),
      catchError(this.someErrorHandler)
    );
}

Solution 3:

One way to do is, return the Observable instead of subscribing in the getPrivateGroup()

getPrivateGroup() {
    console.log('user check', this.user);
    returnthis.groupService.getPrivateGroup(`${this.user.first_name}${this.user.last_name}`)

  }

And then, subscribe to the data where you want the chain the this.loadGroupPosts()

if (this.isItMyWorkplace) {
          this.getPrivateGroup().subscribe(group => {
          this.group = group; //you probably want to assign the group datathis.loadGroupPosts()});
        }

Post a Comment for "Wait For Asynchronous Functions To Finish In Angular"