angular how to await subscribe

You should use async/await if you need synchronous execution of your code. Wrap your subscribe code in a function that returns a promise.

async getRolestypes(): Promise<Array<RoleType>> {

   return new Promise((resolve, reject) => {

     this._roleService.getRoleTypes(this.token).subscribe(
       response => {
         if(response.status != "error" && response.code != 400){
          let _roleTypes:Array<RoleType> = new Array<RoleType>(); 
          _roleTypes = new Array<RoleType>();
          response.data.forEach(rt => {
            let roleType:RoleType = new RoleType(
                rt.id,
                rt.name
            );
            _roleTypes.push(roleType);
           });
          console.log("A");
          console.log(_roleTypes);
          resolve(_roleTypes);
       }
       else{
           this._loginService.destroySession();
           reject('not a good response')
       }
       },error => {
        this.errorMessage = <any>error;
        if(this.errorMessage != null){
           reject(this.errorMessage);
        }
      }
    );


  })


}


this.roleTypes = await getRolestypes();
console.log(this.roleTypes);

you can achieve this using toPromise method. It is also a great way to handle asynchronous operations. Just remove the subscribe and add this method and add the async keyword in the method from where you are calling this method.

Example-

 const response = await this._roleService.getRoleTypes(this.token).toPromise();

So, Now you will get console.log("A") first then console.log("B").


As you may know, subscriptions are used to handle async method call. Thus, the code inside the subscribe() method is executed only when the async method return its result (after a http call for instance).

While waiting for the async response, the program continues and execute the following code. That's the goal of async calls!

That's why your console.log('B') is executed before your console.log('A').

Here is an example:

this.myservice.asyncCall().subscribe( (result) => {
   // wait for the async response
   console.log('I get some data from asyncCall()');
});
// sync code executed, even if the previous async call doesn't respond anything
console.log('Code executed after the subscription. But not waiting for it to respond');

If you want you're console.log('B'), you have to move it into your subscription function (after the else statement). You can also call a method from that location, depending on the purpose you're looking for.

You may take a look at the .map() method as well. This allows you to edit the retrieved response before you handle it in the subscribe method (to add it some data, transform it, log or anything).