How to make synchronous API Request In Angular ?
May 22, 2021
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.
In Service Component :-
//service.tsgetData(url) {
return this.http.get(url)
}
getDataSynchronous(url):Promise<any>{
return this.getData(url).toPromise()
}
In your component :- Using async / await
//mycomponent.ts
async getData(url) {
let data = await this.service.getDataSynchronous(url)
console.log(data)
}
Note : The await
keyword can only be used inside an async
function.
Thanks for reading :)
This is my first medium article and I am trying to write something which help everyone.