Answer the question
In order to leave comments, you need to log in
How do Promises work in Angular?
Faced the problem of not understanding how promises work.
There is an Ionic/Angular app for iOS.
The application has a service where I use native-storage .
async getToken() {
await this.storage.getItem('token')
.then((res) => {
this.token = res
})
}
latest() {
this.getToken()
let options = {
headers: new HttpHeaders({
'auth': this.token
})
}
return this.http.get(this.env.API_URL + 'video', options)
}
getLatestVideo() {
this.videoService.latest()
.subscribe(data => {
this.latestVideo = data;
})
}
async latest() {
await this.getToken()
let options = {
headers: new HttpHeaders({
'auth': this.token
})
}
return await this.http.get(this.env.API_URL + 'video', options)
}
Answer the question
In order to leave comments, you need to log in
this.http.get
returns an Observable, it is an rxjs library object, it is not a promise or thenable and cannot be awaited
You can cast it to a promise like this
return this.http.get(this.env.API_URL + 'video', options).toPromise()
getToken(): Observable<string> {
return from(this.storage.getItem('token'));
}
latest() {
return this.getToken().pipe(
switchMap(token => {
const headers = new HttpHeaders({ auth: token });
return this.http.get(this.env.API_URL + 'video', { headers });
}),
)
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question