【问题标题】:Ionic App convert JSON to arrayIonic App 将 JSON 转换为数组
【发布时间】:2018-04-27 23:38:55
【问题描述】:

我对 Ionic 和 Angular 都很陌生,所以如果这个问题没有多大意义,请原谅。

平台:Ionic 3。

我有一个提供者:rest.ts 如下

getLights() {
  return new Promise(resolve => {
    this.http.get(this.apiUrl+'/lights').subscribe(data => {
      resolve(data);
    }, err => {
      console.log(err);
    });
  });
}

这将返回以下数据(敏感信息已删除)

{
    "1": {
        "state": {
            "on": false,
            "bri": 98,
            "alert": "none",
            "reachable": true
        },
        "swupdate": {
            "state": "noupdates",
            "lastinstall": null
        },
        "type": "Dimmable light",
        "name": "Lion",
        "modelid": "LWB010",
        "manufacturername": "Philips",
    },
    "2": {
        "state": {
            "on": true,
            "bri": 100,
            "alert": "none",
            "reachable": true
        },
        "swupdate": {
            "state": "noupdates",
            "lastinstall": null
        },
        "type": "Dimmable light",
        "name": "Brutus",
        "modelid": "LWB010",
        "manufacturername": "Philips",
    },
    "3": {
        "state": {
            "on": true,
            "bri": 254,
            "hue": 8418,
            "sat": 140,
            "effect": "none",
            "xy": [
                0.4573,
                0.41
            ],
            "ct": 366,
            "alert": "none",
            "colormode": "ct",
            "reachable": true
        },
        "swupdate": {
            "state": "noupdates",
            "lastinstall": null
        },
        "type": "Extended color light",
        "name": "Hue lightstrip plus 1",
        "modelid": "LST002",
        "manufacturername": "Philips"
    }
}

一个离子页面“列表”由:list.ts 组成

export class ListPage {

  lights: any;
  icons: string[];

  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              public restProvider: RestProvider) {

    this.getLights();
  }

  getLights() {
    this.restProvider.getLights()
    .then(data => {
      this.lights = data;
      console.log(this.lights);
    });
  }

}

和 list.html :

<ion-content>
  <ion-list inset>
    <ion-item *ngFor="let light of lights">
      <h2>{{light.name}}</h2>
      <p>{{light.type}}</p>
    </ion-item>
  </ion-list>
</ion-content>

虽然控制台日志语句正确显示 JSON,但由于以下错误,我无法在 list.html 中使用 ngFor 对其进行迭代。

找不到“object”类型的不同支持对象“[object Object]”。 NgFor 只支持绑定到 Arrays 等 Iterables。

我意识到我需要将 JSON 转换为 javascript 数组,但不确定在哪里或如何执行此操作。任何指针将不胜感激。

【问题讨论】:

    标签: angular ionic3


    【解决方案1】:

    有多种方法可以将类似数组的对象转换为数组,具体取决于其组成方式。在这种情况下,您可以很容易地做到这一点:

    data => resolve(Object.keys(data).map(key => data[key]))
    

    这将使用 Promise 中的对象数组进行解析,并且应该与您的组件一起使用。

    我会指出你不必使用自己的Promise,你可以使用Observable方法toPromise

    getLights() {
      return this.http.get(`${this.apiUrl}/lights`).map(data =>
        Object.keys(data).map(key => data[key])
      ).toPromise();
    }
    

    事实上你甚至不需要使用promise,你可以订阅getLights来代替。

    this.restProvider.getLights().subscribe(data => {
      this.lights = data;
    });
    

    注意:

    如果这不是使用 Angular 5,我认为你需要这样做:

    this.http.get(url).map(response => response.json())
    

    也在 Observable 链中。

    【讨论】:

      【解决方案2】:

      感谢您的上述回复。非常有帮助,但不幸的是,我无法按预期工作......可能是因为我缺乏经验。

      我仍然无法解决包含数字作为键的 JSON 并能够遍历灯光的问题....

      但是,我能够投射一盏灯的响应(更改我的 API 调用以获取灯“1”):

      {
      "state": {
         "on": false,
         "bri": 98,
         "alert": "none",
         "reachable": true
      },
      "swupdate": {
        "state": "noupdates",
        "lastinstall": null
      },
      "type": "Dimmable light",
      "name": "Lion",
      "modelid": "LWB010",
      "manufacturername": "Philips",
      }
      

      使用接口:

      export interface State {
      
        on: boolean;
        bri: number;
        alert: string;
        reachable: boolean;
      }
      
      export interface Swupdate {
        state: string;
        lastinstall?: any;
      }
      
      export interface Light {
        state: State;
        swupdate: Swupdate;
        type: string;
        name: string;
        modelid: string;
        manufacturername: string;
        uniqueid: string;
        swversion: string;
        swconfigid: string;
        productid: string;
      }
      

      然后使用 HttpClient 调用来转换对象,如下所示:

      this.http.get<Light>(this.apiUrl+'/lights/1').subscribe(data => {
              console.log(data.state.bri);
      })
      

      如果有人可以详细说明一个界面的结构,该界面可能会成功地投射出一个灯列表,其中键是一个数字,那将是理想的......

      【讨论】:

        猜你喜欢
        • 2017-08-20
        • 2014-05-26
        • 2011-01-18
        • 1970-01-01
        • 1970-01-01
        • 2020-12-31
        相关资源
        最近更新 更多