首页 > 解决方案 > 从服务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 以进一步使用它。

标签: angularhttpangular-promise

解决方案


我猜你的问题是那些行:

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();

推荐阅读