R
R
Roman Khegay2020-02-13 10:39:25
JavaScript
Roman Khegay, 2020-02-13 10:39:25

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
    })
}


Also, the service has a function by which I request data from the server:
latest() {
        this.getToken()

        let options = {
            headers: new HttpHeaders({
                'auth': this.token
            })
        }

        return this.http.get(this.env.API_URL + 'video', options)
    }


And there is a view in which I call a function from the service:
getLatestVideo() {
        this.videoService.latest()
            .subscribe(data => {
                this.latestVideo = data;
            })
    }


Problem:
When I call the async/await getToken() function and then I contact the server, the request to the server leaves null in the token. If I change the function to async/await:
async latest() {
        await this.getToken()

        let options = {
            headers: new HttpHeaders({
                'auth': this.token
            })
        }

        return await this.http.get(this.env.API_URL + 'video', options)
    }


then, in this case, the .subscribe() function in the view does not work.

Maybe someone can explain how Promises work and what I'm doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shvets, 2020-02-13
@khegay

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()

However, it is normal practice in Angular to avoid promises.
And your methods should look like this
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 question

Ask a Question

731 491 924 answers to any question