So, I was trying to get the solution of this problem. But, somehow I am unable to do so, May be because of the lack of knowledge in angular 5. This is my service:
GetCurrentUserData(): Observable<ResponseData> {
return this.http.get<ResponseData>(ApplicationURLS.GetCurrentUserInformation)
.map(response => {
return response;
});
//.catch(error => this.handleError(error));
}
This is my component:
public GetCurrentUserInformation(): any {
return this.loginService.GetCurrentUserData().subscribe(data => { return data; });
}
Here I am trying to access the data:
ngAfterViewInit() {
debugger;
this.responseData = this.GetCurrentUserInformation();
if (this.responseData.code != responseCodes.success) {
this.googleInit();
}
}
When I check the this.responseData it is always returning this instead I want data:
I just want to make a sync call so I can get the data immediately.
I also tried to use the do() in service but its returning do() is not a function.
Synchronous HTTP calls in Angular using Async and Await In that case, we use Async and Await functions to achieve this. An asynchronous function is a function which operates asynchronously via the event loop, using an implicit Promise to return its result.
1.1 The Angular HTTP Client The API is asynchronous.
A common misconception in Angular development is regarding whether observables are synchronous or asynchronous. A lot of (even experienced Angular developers) think that observables are async, but the truth is that they can be… Both synchronous and asynchronous.
Synchronous means that you call a web service (or function or whatever) and wait until it returns - all other code execution and user interaction is stopped until the call returns. Asynchronous means that you do not halt all other operations while waiting for the web service call to return.
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();
}
});
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