How to make a synchronous call in angular 5?

Just code picture Just code · Dec 2, 2017 · Viewed 75.1k times · Source

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: enter image description here

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.

Answer

malbarmavi picture malbarmavi · Jul 26, 2019

this can be simplify 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();
        }
    }