由于某种原因,当我注销控制台时,我的.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()中的游戏返回的是可观察值,而不是我期望从服务器/数据库取回的数据。
问题是角度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,则不应使用promisethen()
方法。相反,它应该类似于:
async getGames() {
const game = await this.games.getAllGames(this.currentPage);
this.gamesArray = game;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句