我正在学习 https://angular.io/tutorial/toh-pt6 上的 Angular 教程它展示了如何从 API 调用中检索 Json 响应,然后将其与 promise 匹配。
具体例子是:
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError);
}
我正在使用 AWS API 网关,其使用详情请参阅 http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-generate-sdk-javascript.html
作为 Typescript 和 promises 的新手,我该如何修改示例方法以适应 Angular 教程的结构?
apigClient.methodName(params, body, additionalParams)
.then(function(result){
// Add success callback code here.
}).catch( function(result){
// Add error callback code here.
});
在我的示例中,result.data 是一个 JSON 对象数组。
最佳答案
您应该为您的客户端 API 调用创建如下所示的 Promise 包装器 -
getResult(): Promise<any> {
return new Promise((resolve, reject) => {
apigClient.methodName(params, body, additionalParams)
.then(function(result){
resolve(result)
}).catch( function(result){
reject(result)
});
})
}
关于javascript - Angular - 返回 API 响应作为 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45261980/