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);
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.
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.
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.
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").
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With