How to wait for a http request to finish in Angular?

前端 未结 3 968
野的像风
野的像风 2021-02-07 09:42

I\'ve been building a SPA with Angular 4 on the front end and ASP.NET Core 2 on the Backend. Basically, I\'m trying to automatically renew an user login, given a valid token. Wh

相关标签:
3条回答
  • 2021-02-07 10:01

    You can use promises with async/await

    async getUser() {
        if (this.storage.token == null || this.storage.token == '') {
            return;
        }
    
        const t = await this.net.get<LoginModel>(`Authentication/GetUser`).toPromise();
    
        this.storage.token = t.token;
        this.storage.user = t.user;
    
        console.log(this.storage.user);
    }
    

    See more:

    • Promises
    • async
    • await
    • ES8 async/await
    • async/await tutorial
    • async/await explained
    0 讨论(0)
  • 2021-02-07 10:19

    You can not use the async/await syntax with Observables returned by Angular HttpClient so you first need to convert the observable to a promise first.

    Luckily the Observable interface exports a toPromise() method which returns a promise from the observable:

    await this.net.get<LoginModel>('Authentication/GetUser').toPromise();
    

    See this example of how to use Async/Await with Angular HttpClient

    0 讨论(0)
  • 2021-02-07 10:21

    Use .toPromise on your observable followed by async/await.

    await this.net.get<LoginModel>(`Authentication/GetUser`).toPromise();
    
    0 讨论(0)
提交回复
热议问题