Reputation: 217
I want to use my API asynchronously. I get some data from my API and i need to display them.
Here an example :
home.ts
async ngOnInit()
{
console.log("NgInit 01");
this.data = await this.api.getMe();
console.log("NgInit 02");
this.canDisplayData = true;
}
home.html
<div *ngif="canDisplayData">
myData : {{ data }}
</div>
service_api.ts
async getMe() {
let result: any;
await this.http.get('http://dummy.restapiexample.com/api/v1/employees')
.toPromise()
.then(res => { result = res; })
.catch(error => { console.log(error); });
return result;
}
this works, but i'm not proud at all of it. I'm sure i can do something better. Without use async
and await
.
Thank you for teaching me life, of angular/ionic :D
Upvotes: 1
Views: 4976
Reputation: 24406
async/awit work on promise only so you need to convert observable to promise
service_api.ts
getMe() {
return this.http.get('http://dummy.restapiexample.com/api/v1/employees')
}
home.ts
async ngOnInit()
{
console.log("NgInit 01");
this.data = await this.api.getMe().toPromise();
console.log("NgInit 02");
this.canDisplayData = true;
}
another way is to use async pipe 🚀🚀
async/awit work on promise only so you need to convert observable to promise
service_api.ts
getMe() {
return this.http.get('http://dummy.restapiexample.com/api/v1/employees');
}
home.ts
ngOnInit()
{
console.log("NgInit 01");
this.data$ = this.api.getMe();
console.log("NgInit 02");
}
tenplate
<div >
myData : {{ data$ | async}}
</div>
Upvotes: 1
Reputation: 246
You can go with below one, async and await can slow your app.
Home.ts
ngOnInit()
{
this.api.getMe().subscribe((data)=>{
this.canDisplayData = true;
this.data = data;
}, (err) => {
console.log(err);
});
}
Home.html
<div *ngif="canDisplayData">
myData : {{ data }}
</div>
service_api.ts
getMe() {
return this.http.get('http://dummy.restapiexample.com/api/v1/employees');
}
Upvotes: 0
Reputation: 86730
I personally don't recommend to use async and await with angular when we have observable and subscribe of rxJs, just convert your code like this save extra variables too -
ngOnInit() {
this.api.getMe()
.subscribe(res => {
this.data = res;
},
error => {
console.log(error);
});
}
<div>
myData : {{ data }}
</div>
getMe() {
return this.http.get('http://dummy.restapiexample.com/api/v1/employees')
.map(res => {
return res;
});
}
Upvotes: 0