Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular how to await subscribe

Tags:

I am newbie regarding Angular applications. I don't understand exactly how subscribe works. My current blocker is that I don't understand why the console.log("B") is executed before the console.log("A"), consequently presenting the result of an empty array (see the links to console output).

I tried to put all the code in a function with async/await to wait for the function. I don't understand why it doesn't work.

What is the best way in this case to wait for a subscription?

The console.log("B") must be executed after the console.log("A").

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);             this.roleTypes = _roleTypes;         }         else{             this._loginService.destroySession();         }     },error => {         this.errorMessage = <any>error;         if(this.errorMessage != null){             console.log(this.errorMessage);             alert("Petition Error");         }     } ); console.log("B"); console.log(this.roleTypes); 
  • code
  • console
like image 414
Jon Doe Avatar asked Jan 10 '18 10:01

Jon Doe


People also ask

How do you await subscribe method?

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. const response = await this.

Does subscribe wait for response Angular?

Basically the console. log(this. newIds) is runned first and is always empty because the subscribe doesn't wait for response to come from the backend.

Is subscribe asynchronous in Angular?

Descriptionlink. The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes.


1 Answers

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").

like image 75
Sunny Avatar answered Oct 20 '22 06:10

Sunny