尝试找出异步返回可观察到的问题

时间:2019-10-17 23:28:41

标签: angular typescript observable

由于某种原因,当我注销控制台时,我的.then()给我一个可观察的东西,有没有办法获取返回的数据?

我尝试了多种方法来解决异步/等待问题,但是我似乎不知道该怎么办。现在看来,我的页面正在加载,然后数据通过并导致控制台中引发错误。数据最终会通过,但不会在引发错误之前出现。

这是我的内容ts:

async getGames() {
    await this.games.getAllGames(this.currentPage).then(game => {
      this.gamesArray = game;
    });
}

这来自我的服务文件

async getAllGames(page) {
    console.log('11111111111111');
    const queryParams = `?page=${page}`;
    return await this.http.get(this.url + queryParams);
}

这是我的html

<div class="col-lg-9 float-right">
    <!-- <div *ngIf='loading'  class="d-flex justify-content-center">
      <div class="spinner-border" style="width: 3rem; height: 3rem;" role="status"></div>
    </div> -->
    <!-- <div *ngIf="!loading"> -->
    <div class="row">
        <div class="col-lg-6 card-background" *ngFor="let game of gamesArray.games">
            <div class="card-surround shadow-sm">
                <div>
                    <h2>{{game.homeTeam.teamName}}</h2>
                    <h2>{{game.awayTeam.teamName}}</h2>
                    <canvas id="{{game.id}}"></canvas>
                    <hr>
                    <p>{{game.gameTime}}</p>
                </div>
            </div>
        </div>
    </div>
    <!-- </div> -->
    <ngb-pagination class="d-flex justify-content-end" 
        size="sm" 
        [collectionSize]="gamesArray.games.length" 
        [(page)]="currentPage"
        [maxSize]="5" 
        [pageSize]='6'                  
        [rotate]="true" 
        [ellipses]="false"
        [boundaryLinks]="true"
        (pageChange)='onPageChange($event)'>
    </ngb-pagination>
</div>

问题在于then()中的游戏返回的是可观察值,而不是我期望从服务器/数据库取回的数据。

2 个答案:

答案 0 :(得分:2)

同意@alexortizl,您只需要在toPromise()的返回值上调用getAllGames()就可以了。

async getAllGames(page) {
      console.log('11111111111111');
      const queryParams = `?page=${page}`;
      return await this.http.get(this.url + queryParams).toPromise(); // <--- like this
    }

我想补充一点,您也可以通过调用this.http.get(...)使用可观察的自身。您只需要致电subscribe而不是then

看看这个stackblitz项目,看看代码是什么样子。 https://stackblitz.com/edit/angular-j7bh6e?file=src%2Fapp%2Fgame.service.ts

答案 1 :(得分:1)

问题在于角度http.get()返回一个Observable,因此在getAllGames()函数中,您说:

return await this.http.get(this.url + queryParams);

您实际上返回的是Observable而不是Promise。应该是这样的:

return await this.http.get(this.url + queryParams).toPromise();

同样在getGames()函数中,如果您使用await,则不应使用promise then()方法。相反,它应该类似于:

async getGames() {    
    const game = await this.games.getAllGames(this.currentPage);
    this.gamesArray = game;
  }