当我依次调用函数时,变量值设置不正确

时间:2018-09-20 07:21:39

标签: angular promise angular6

我是新手。我的问题是关于向服务器端发送ajax请求,它们的接收顺序很重要。

adminList = null;
ngOnInit() {
  this.getAdminsList();
  this.getRolesList();
  this.getListOfPermissions();
}

getAdminsList(){
    this.http.get(AppSetting.adminApiRootUrl + '/admins', {
      headers: new HttpHeaders({
        'Accept': 'application/json',
        'Authorization': 'Bearer ' + localStorage.getItem('auth_token')
      })
    }).subscribe((response) => {
      this.adminList = response['entire'].list;
    });
}

通过编写这些代码,我实现了一些变量,例如adminList在html文件中没有正确的值。

之后,我使用了Promise,如下所示:

ngOnInit() {
  this.getAdminsList().then((res) => {
    this.adminList = res;
    this.getListOfPermissions().then((res2) => {
      this.permissionsList = res2;
      this.getRolesList().then((res3) => {
        this.rolesList = res3;
        this.fillRolesIntoForm().then((res4) => {
        });
      });
    });
  });
  console.log(this.adminList)
}

getAdminsList() {
  return new Promise((resolve, reject) => {
    this.http.get(AppSetting.adminApiRootUrl + '/admins', {
         headers: new HttpHeaders({
        'Accept': 'application/json',
        'Authorization': 'Bearer ' + localStorage.getItem('auth_token')
      })
    }).subscribe((response) => {
      let adminList = response['entire'].list;
      resolve(adminList);
    });
  });

}

但是当在ngOnInit函数的末尾写入console.log(this.adminList)时,它将返回null。

我,你帮我怎么了?

2 个答案:

答案 0 :(得分:0)

您可以使用以下方法实现它。

ngOnInit() {
  this.getAdminsList();
}
getAdminsList(){
   this.http.get(AppSetting.adminApiRootUrl + '/admins', {
  headers: new HttpHeaders({
    'Accept': 'application/json',
    'Authorization': 'Bearer ' + localStorage.getItem('auth_token')
  })
}).subscribe((response) => {
  this.adminList = response['entire'].list;
  this.getRolesList();
});
}

答案 1 :(得分:-1)

如果要获取所有API的响应,然后再通过HTML显示。然后尝试使用角度为4/5的forkjoin概念。

参考:通过此链接-https://medium.com/@swarnakishore/performing-multiple-http-requests-in-angular-4-5-with-forkjoin-74f3ac166d61

希望有帮助!