angular - 如何从提供者中的承诺将此数据返回到组件
问题描述
下面的代码显示了我在组件中的调用。
getLocations
是在provider
.
我无法理解如何将数据返回到组件以显示给用户。我可以在控制台中看到格式的数据,[{},{}]
但需要在前端访问使用它。
我对 Angular 很陌生,这是我第一次尝试使用component/provider/promise
.
任何帮助/建议将不胜感激。
这是 Angular 5 的最佳实践吗?对不起我的无知。
constructor(public navCtrl: NavController, public navParams: NavParams, public loginProvider: LoginProvider, public alertCtrl: AlertController) {
this.loginProvider.getLocations();
}
getLocations() {
let promise = new Promise((resolve, reject) => {
let apiURL = 'http://xxxx-dev.xxxxxxx.com/api/default/v1/locations';
this.http.get(apiURL)
.toPromise()
.then(
res => { // Success
this.locations = res.json();
console.log(this.locations);
resolve();
}
);
});
return promise;
}
解决方案
如果您在其他方法调用中需要请求的结果,您应该在 onfulfilled(success) 函数中返回它,如下所示:
getLocations() {
let apiURL = 'http://xxxx-dev.xxxxxxx.com/api/default/v1/locations';
return this.http.get(apiURL)
.toPromise()
.then(
(success) => {
this.locations = res.json();
console.log(this.locations);
return success;
}
);
}
otherMethod() {
getLocations().then(
(res) => {
//you see result of query that returned in http request
}
);
}
}
推荐阅读
- node.js - mongodb:查询日历模型中的空闲时间段
- angular - Angular:有条件地导入模块不适用于 AoT
- excel - Excel VBA 中的“无法设置字体类的大小属性”错误,用于条件格式,工作表不受保护
- matlab - 绘制脉冲函数
- python - 在 python 中绘制数组的问题
- elasticsearch - 尝试更新 elasticsearch 中的嵌套 geoip 位置字段
- c# - 实体框架不生成实体类
- laravel - LARAVEL 获取文件内容并拆分以保存在另一个表中
- angular - Docker - standard_init_linux.go:211:exec 用户进程导致“exec 格式错误”树莓派
- outlook - Outlook for iOS 中带有 Exchange.Callback.V2 令牌的 InvalidAudienceForResource 异常