Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 synchronous HTTP call

I have an Angular 5 application in which I have to call some heavy REST service (usually takes some seconds). I need its result in different part of application, so I would like to store the result in a DataStorageService. Basically, this is I would like to achieve:

@Injectable()
export class DataStorageService {

private result: MyCustomObject;

constructor(private service: Service) {}

getResult(): MyCustomObject {
    if (typeof this.result === 'undefined') {
        // save result
    }
    return result;
}

The question is how I can wait until HTTP request is finished and then save and return the 'result' object. I tried to solve it using Promise and Observable as well, but none of them worked fine.

  1. Observable:

    if (typeof this.result === 'undefined') {
        this.service.call()
            .subscribe(response => this.result = response);
    }
    return this.result;  // wait for save and return MyCustomObject
    
  2. Promise:

    if (typeof this.result === 'undefined') {
        this.service.call()
            .toPromise()
            .then(response => this.result = response);
    }
    return this.result;  // wait for save and return MyCustomObject
    
like image 378
aszidien Avatar asked Mar 23 '18 07:03

aszidien


People also ask

How to make synchronous api calls in Angular?

Let you have getData() function to call an api , which fetch data asynchronous , but to make synchronous api call, let's wrap this function inside a another function to make a call that return to promise and use async/await in component.

Is HTTP request is synchronous or asynchronous in angular?

1.1 The Angular HTTP Client It is a wrapper over the JavaScript XMLHttpRequest API. The API is asynchronous. JavaScript is single-threaded. Doing a blocking synchronous HTTP call will otherwise freeze the UI.

Is angular API calls asynchronous?

Angular is a great framework but writing asynchronous code and making asynchronous calls is hard. Especially if you can't decide between Async/Await and Angular Promise.

What is difference between asynchronous and synchronous in angular?

The differences between asynchronous and synchronous include: Async is multi-thread, which means operations or programs can run in parallel. Sync is single-thread, so only one operation or program will run at a time.


1 Answers

Try using await/async

async getResult(): Promise<MyCustomObject> {
    if (typeof this.result === 'undefined') 
    {
        // save result
        this.result = await this.service.call()
        .toPromise()
        .then(resp =>resp as MyCustomObject);//Do you own cast here

    }
    return this.result;
}
like image 127
David Avatar answered Oct 15 '22 21:10

David