等待异步函数在Angular中完成

时间:2018-12-17 14:51:11

标签: javascript angular asynchronous

所以我正在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--! //

3 个答案:

答案 0 :(得分:3)

您可以将基本承诺与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;
      });

}

答案 1 :(得分:1)

您可以改为使用RxJS并使用switchMap这样的内容(不检查语法):

  ---------------------------------------------------------------------------
IsADirectoryError                         Traceback (most recent call last)
<ipython-input-40-fdb88fbf61ab> in <module>()
     29             read_file = csv.read()
     30     else:
---> 31             with open(file,"rt", encoding='latin-1') as allOtherFiles:
     32                 continue
     33     if regex1.findall(read_file) or regex2.findall(read_file) or regex3.findall(read_file):

IsADirectoryError: [Errno 21] Is a directory: '/home/jupyter_shared_notebooks'

答案 2 :(得分:0)

一种方法是返回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()});
        }