簡體   English   中英

等待異步函數在 Angular 中完成

[英]wait for asynchronous functions to finish in Angular

所以我在 Angular 和 ngOninit 中開發一個新組件,我在下面有以下異步函數......

This.getUserProfile 需要在我調用 this.getPrivateGroup() 之前完成,而 this.getPrivateGroup() 需要在我調用 this.loadGroupPosts() 之前完成。 我知道我可以在異步請求的回調中編寫這些函數,但我想知道是否有辦法將它保留在 ngOnInit 中以使其更干凈?

有人有想法嗎?

ngOnInit() {

    this.getUserProfile();

    // 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 post
    if (this.isItMyWorkplace) {
      this.getPrivateGroup();
    }
    this.loadGroupPosts();
  }

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}`;
      }, (err) => {
        this.alert.class = 'alert alert-danger';
        if (err.status === 401) {
          this.alert.message = err.error.message;
          setTimeout(() => {
            localStorage.clear();
            this._router.navigate(['']);
          }, 3000);
        } else if (err.status) {
          this.alert.class = err.error.message;
        } else {
          this.alert.message = 'Error! either server is down or no internet connection';
        }
      });
  }



getPrivateGroup() {
    console.log('user check', this.user);
    this.groupService.getPrivateGroup(`${this.user.first_name}${this.user.last_name}`)
      .subscribe((group) => {
          console.log('received response', group)
    })
  }

 // !--LOAD ALL THE GROUP POSTS ON INIT--! //
  loadGroupPosts() {
    this.isLoading$.next(true);

    this.postService.getGroupPosts(this.group_id)
      .subscribe((res) => {
        // console.log('Group posts:', res);
        this.posts = res['posts'];
        console.log('Group posts:', this.posts);
        this.isLoading$.next(false);
        this.show_new_posts_badge = 0;
      }, (err) => {
        swal("Error!", "Error while retrieving the posts " + err, "danger");
      });
  }
  // !--LOAD ALL THE GROUP POSTS ON INIT--! //

您可以將基本承諾與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 post
    if (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}`;
        return true; // <-- 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);
        } else if (err.status) {
          this.alert.class = err.error.message;
        } else {
          this.alert.message = 'Error! either server is down or no internet connection';
        }
        throw err;
      });

}

您可以改為利用 RxJS 並使用類似這樣的 switchMap(未檢查語法):

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

一種方法是返回 Observable 而不是訂閱getPrivateGroup()

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

  }

然后,訂閱你想要鏈接的數據this.loadGroupPosts()

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

您也可以在完成后使用訂閱功能的第三部分我不太確定這是否是一個干凈的解決方案,在我看來是這樣。

ngOnInit() {
this.getUserProfile();
}


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}`;
    }, (err) => {
        this.alert.class = 'alert alert-danger';
        if (err.status === 401) {
            this.alert.message = err.error.message;
            setTimeout(() => {
                localStorage.clear();
                this._router.navigate(['']);
            }, 3000);
        } else if (err.status) {
            this.alert.class = err.error.message;
        } else {
            this.alert.message = 'Error! either server is down or no internet connection';
        }
    }, () => {
        // 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 post
        if (this.isItMyWorkplace) {
            this.getPrivateGroup();
        }
    });
}

getPrivateGroup() {
console.log('user check', this.user);
this.groupService.getPrivateGroup(`${this.user.first_name}${this.user.last_name}`)
    .subscribe((group) => {
        console.log('received response', group)
    }, error => {
        console.log(error)
    }, () => {
        this.loadGroupPosts();
    })
}

loadGroupPosts() {
this.isLoading$.next(true);

this.postService.getGroupPosts(this.group_id)
    .subscribe((res) => {
        // console.log('Group posts:', res);
        this.posts = res['posts'];
        console.log('Group posts:', this.posts);
        this.isLoading$.next(false);
        this.show_new_posts_badge = 0;
    }, (err) => {
        swal("Error!", "Error while retrieving the posts " + err, "danger");
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM