Reputation: 675
I have two methods, and I want to await result before executing furder code. I try with async before func name and await before GetNavigationData(), but no results. I also try to print values to see what's going on, and expected data should be:
API method
Regular method
getFlatNavigation(navigation) {
if (this.navigation.length == 0) {
console.log(this.GetNavigationData());
console.log('Regular method');
}
}
GetNavigationData() {
let applicationMenuData = new InitializeAppRequest();
this.http.post(this.appGlobal.BASE_SERVER_ADDRESS + 'api/AppServer/InitializeApp', applicationMenuData).subscribe((res) => {
console.log('API method');
return res['AplicationMenuData'];
});
}
How to get expected results?
Upvotes: 0
Views: 87
Reputation: 39482
async
/await
requires you to use Promise
but since Angular has moved on with Observables, you could simply use that syntax instead.
You could return an Observable
from the GetNavigationData
method and then subscribe to it in the getFlatNavigation
where you're calling GetNavigationData
getFlatNavigation(navigation) {
if (this.navigation.length == 0) {
this.GetNavigationData()
.subscribe(res => {
console.log(res);
console.log('Regular method');
})
}
}
GetNavigationData() {
let applicationMenuData = new InitializeAppRequest();
return this.http.post(this.appGlobal.BASE_SERVER_ADDRESS + 'api/AppServer/InitializeApp', applicationMenuData)
.pipe(
map(res => {
console.log('API method');
return res['AplicationMenuData'];
})
);
}
Upvotes: 0
Reputation: 1
async getFlatNavigation(navigation) {
if (this.navigation.length == 0) {
console.log(await this.GetNavigationData());
console.log('Regular method');
}
}
async GetNavigationData() {
let applicationMenuData = new InitializeAppRequest();
this.http.post(this.appGlobal.BASE_SERVER_ADDRESS + 'api/AppServer/InitializeApp', applicationMenuData).subscribe((res) => {
console.log('API`enter code here` method');
return res['AplicationMenuData'];
});
}
Upvotes: 0
Reputation: 8295
You can use async/await
async getFlatNavigation(navigation) {
if (this.navigation.length == 0) {
console.log(await this.GetNavigationData());
console.log('Regular method');
}
}
GetNavigationData() {
let applicationMenuData = new InitializeAppRequest();
return this.http
.post(this.appGlobal.BASE_SERVER_ADDRESS + 'api/AppServer/InitializeApp', applicationMenuData)
.pipe(
map((res) => {
console.log('API method');
return res['AplicationMenuData'];
})
)
.toPromise();
}
Upvotes: 1