【发布时间】:2018-05-14 06:21:13
【问题描述】:
所以在这里我将通过调用this.Reload.All() 来初始化我的数组,然后获取我需要的所有数组,以便稍后在程序中进行过滤。发生的情况是所有 4 个调用都发出 然后 4 个响应返回。这会混淆并破坏服务,因为它在回复他们的响应之前无法接听这么多电话。我正在寻找的是一个同步解决方案,它会做这样的事情:调用 1 - 响应 1 - 调用 2 - 响应 2 - 调用 3 - 响应 3 - 调用 4 - 响应 4。 reponse.dbX_response.view 就是这样我的 JSON 从服务器返回。
我的所有代码都正常工作,只是异步中断了我的调用。我该如何解决这个问题?
//Reload Reference Arrays
RefVehicleTypes = [];
RefClients = [];
RefUsers = [];
RefObjects = [];
//Reload Class:
Reload = {
DoCall : (pUrl, pArray, pResponse) => {
this.HttpClient.get(pUrl).subscribe(
(response: any) => {
this[pArray] = eval(pResponse);
console.log(pResponse + ' : ' + this[pArray]);
}
);
},
All : () => {
this.Reload.VehicleTypes();
this.Reload.Clients();
this.Reload.Users();
this.Reload.Objects();
},
VehicleTypes : () => {
this.Reload.DoCall(
'http://...',
'RefVehicleTypes',
'response.dbVehicleType_response.view',
);
},
Clients : () => {
this.Reload.DoCall(
'http://...',
'RefClients',
'response.dbClient_response.view',
);
},
Users : () => {
this.Reload.DoCall(
'http://...',
'RefUsers',
'response.dbUser_response.view'
);
},
Objects : () => {
this.Reload.DoCall(
'http://...',
'RefObjects',
'response.dbObject_response.view'
);
}
}
新编辑:
所以我用这个替换了 DoCall 和 All 方法,但这仍然不起作用。查看下面的屏幕截图以了解结果。
DoCall : (pUrl, pArray, pResponse) => {
return new Promise((resolve, reject) => {
this.HttpClient.get(pUrl).subscribe(
(response: any) => {
console.log('##############################' + pArray)
console.log(this[pArray]);
this[pArray] = eval(pResponse);
console.log(this[pArray]);
resolve();
}
)
});
},
All : async () => {
await this.Reload.VehicleTypes();
await this.Reload.Clients();
await this.Reload.Users();
await this.Reload.Objects();
},
这里是 3 次刷新的 3 张截图。如您所见,异步 All() 函数似乎导致数组混合在一起,这没关系。不知道为什么,但它仍然以某种方式延迟了响应。最后一个总是有效,这可能意味着之前的响应正在被下一个响应所取代?
【问题讨论】:
-
在
DoCall方法中返回一个promise 并在All方法中链接命令或使用await -
Fussel 你介意写一个基本的例子吗?我对 Angular 很陌生,而且 Promise 很棘手
标签: angular typescript http httpclient