I'm developing mobile application, using Ionic 4 & Angular 8. And I have some troubles, trying to achieve simple tasks.
So, I'm using: @ionic-native/native-storage & @angular/http in Angular service like this:
async getToken() {
await this.storage.getItem('token')
.then((res) => {
this.token = res
})
}
This is an Promise resolving function, am I right?
Then, I need to call this async/await function in another function:
latest() {
this.getToken()
let options = {
headers: new HttpHeaders({
'Auth-Key': this.token
})
}
return this.http.get(this.env.API_URL + 'url', options)
}
Next step is call service function from the page:
getLatestVideo() {
this.videoService.latest()
.subscribe(data => {
this.latestVideo = data;
})
}
And now the problem:
The function getting 'token' from storage, did not finished, and Promise did not resolved, when I'm trying to get this token.
So, when I call HttpClient, and trying to get some data from api, I get an error, that says: 'token, you trying to call is null'.
Can someone explain how is Promises works? I can't get it
UPDATE 1:
Problem is resolved by 2 steps: Step 1: Make latest() async
async latest() {
await this.getToken()
let options = {
headers: new HttpHeaders({
'Auth-Key': this.token
})
}
return this.http.get(this.env.API_URL + 'url', options)
}
Step 2: Make getLatestVideo() async too
async getLatestVideo() {
const latestVideo = await this.videoService.latest();
latestVideo.subscribe(data => {
this.latestVideo = data;
})
}
New problem: How to display data after all promises resolved inside view:
<div *ngFor="let video of latestVideo">{{ video.id }}</div>