How to make a synchronous call in angular 5?
This can be simplified by using async/await
🔥🔥
public GetCurrentUserInformation(): Promise<any>{ return this.loginService.GetCurrentUserData().toPromise()}
ngAfterViewInit
async ngAfterViewInit() { this.responseData = await this.GetCurrentUserInformation(); // 🧙♂️ if (this.responseData.code != responseCodes.success) { this.googleInit(); } }
Subscribe to GetCurrentUserData()
the http call is async (every browser api call is async, because the javascript engine runs in a single thread (google for browser event loop for more, this is not an angular issue))
this.GetCurrentUserInformation().subscribe((data: ResponseData) => { if (this.responseData.code != responseCodes.success) { this.googleInit(); }});
Asynchronous functions cannot be called synchronously, because they are asynchronous.
subscribe
generally shouldn't performed in methods that are expected to be chained. Even if it should, an observable and not a subscription should be returned from a method (a subscription can be additionally saved to be unsubscribed on destruction).
GetCurrentUserInformation
method is redundant because it is just a wrapper for service call. The code can be refactored to:
ngAfterViewInit() { this.loginService.GetCurrentUserData().subscribe(data => { this.responseData = data; if (this.responseData.code != responseCodes.success) { this.googleInit(); } });}