0

I'm new in angular. My question is about sending ajax request to server side which their receiving sequences are important.

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;
    });
}

By writing these code, I realize some variable e.g. adminList doesn't get correct value in html file.

After that I used Promise like below:

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);
    });
  });

}

But when is write console.log(this.adminList) at the end of ngOnInit function it returns null.

my you help me what is the problem?

farhad.a
  • 341
  • 4
  • 17

2 Answers2

0

You can achieve it using the following.

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();
});
}
shubham singh
  • 400
  • 2
  • 7
-1

If you want to get response from all API's and after that you want it to show over HTML. Then try using forkjoin concept of angular 4/5.

For ref : Go through this link - https://medium.com/@swarnakishore/performing-multiple-http-requests-in-angular-4-5-with-forkjoin-74f3ac166d61

Hope it helps !!

Anshu Bansal
  • 344
  • 2
  • 4