angular - 从服务Angular 5返回后使用承诺
问题描述
在 Angular 应用程序中,我在 assets 文件夹中创建了一个“config.json”,其中存储了一些有关应用程序的设置以供进一步使用。
config.json 中的 json 数据是
{
"config":{
"worker_url":"http//:domainname/abc"
}
}
从我的组件中,我调用了一个服务方法来从 config.json 获取数据。
this.app_config = this._configService.getConfigResponse().then( (res) => {
return res;
});
// app_config is Object;
console.log(this.app_config);
我在服务中有一个名为“ConfigServices”的功能
getConfigResponse() {
let promise = new Promise((resolve, reject) => {
let apiURL = this._configFilePath;
this.http.get(apiURL)
.toPromise()
.then(
res => { // Success
this.results = res.json().config;
// console.log(res.json().config);
resolve(this.results);
},
msg => { // Error
reject(msg);
}
);
});
return promise;
}
控制台日志中的结果是:
不明白如何在数组中获取此 json 以进一步使用它。
解决方案
我猜你的问题是那些行:
this.app_config = this._configService.getConfigResponse().then( (res) => {
return res;
});
尝试将其重写为
this._configService.getConfigResponse().then( (res) => {
this.app_config = res;
});
如果可以使用 async/await,则可以将代码重写为:
this.app_config = await this._configService.getConfigResponse();
推荐阅读
- c++ - 将 Json 对象转换为字符串
- user-interface - 如何实现 Flutter CustomPainter 在图像上准确渲染?
- python - python:保持数据库打开/或重新连接的最佳方法
- c - 仅使用循环的非重复组 6 个随机数
- reactjs - React 编辑按钮 + 填充输入字段(PUT METHOD/PUT REQUEST)
- python - Signal.NEWNYM 在scrapy中间件中使用时不提供新的IP地址
- javascript - 通过 react-native 导航传递参数
- python - WebScraping - 从 td 类中提取值
- node.js - Mongodb 聚合 $limit 不返回文档
- ruby-on-rails - 从 rails 5.1 迁移到 5.2 后,模型重新索引时出现错误“TypeError: no implicit conversion of nil into Hash”