【发布时间】:2020-08-21 15:30:17
【问题描述】:
我尝试使用异步/等待数据库加载来实现加载微调器,但无法在我的异步方法中命中代码。 我的数据加载看起来像这样
getServerList(){
this.http.get('XXXX')
.map((data : Response) =>{
return data.json() as MyObject[];
}).toPromise().then(x => {
this.serverList = x;
})
}
我的组件内部的功能是
async () => {
try {
await this.serverListService.getServerList()
}catch{}
}
首先,我有一个警告告诉我,我的 await 关键字没有用,因为没有什么可以等待。所以我决定像这样在我的数据加载中添加一个异步关键字
async getServerList(){
this.http.get('http://localhost:6875/api/ServerList_Base')
.map((data : Response) =>{
return data.json() as ServerListBase[];
}).toPromise().then(x => {
return x;
})
return this.serverList
}
所以现在我的 await 很有用,但我的问题是代码永远不会在我的异步括号内。我的意思是里面的代码
async () => {}
从未被执行,我不知道为什么。我试图从构造函数/从 ngAfterViewInit 的 nginit 中加载它,但没有任何效果
而且当我尝试像这样删除这些异步括号时
async loadDataFromDB(){
await this.serverListService.getServerList()
this.dataSource = new MatTableDataSource()
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
this.showSpinner = false;
}
在转到第二行“this.dataSource”之前不会等待 getServerList()... 我习惯在 c# 中使用 async/await,也许我错过了一些 angular 的东西。 提前致谢
【问题讨论】:
-
取
getServerList()的第一个版本,将return添加到第一行(return this.http.get('XXXX') ...)。你不能等待不返回承诺的东西。 -
你为什么要把 promise 和 async/await 混在一起,挑一个来用吧
-
getServerList需要返回承诺:async getServerList(){ return this.http.get('http://localhost:6875/api/ServerList_Base')... -
.toPromise().then(x => { return x; })实际上什么也没做 -
@liam 好的,谢谢,我想我需要更深入地了解一下 promise 的工作原理..
标签: angular asynchronous async-await angular7