首页 > 解决方案 > 如何在 Typescript 中依次执行 2 个函数?

问题描述

我正在调用以下两个函数:

getStudentDataFunction(){
........
return studentData
}

getTeachersDataFunction(){
........
return teachersData
}

我希望在 getStudentDataFunction() 完成返回数据后执行 getTeachersDataFunction()。

有没有办法做到这一点?

标签: javascripttypescript

解决方案


您可能需要使用 Rxjs 使这两个方法可观察,因此您可以执行以下操作:

  caller() {
    this.method1()
      .pipe(switchMap(res1 => this.method2(res1)))
      .subscribe(res2 => {
        console.log(res2);
      });
  }

另请参阅演示:https ://stackblitz.com/edit/angular-ivy-rn5kfe?file=src/app/app.component.ts


推荐阅读