【问题标题】:How i can read an Object within ionic 2 and angular 2?我如何在 ionic 2 和 angular 2 中读取对象?
【发布时间】:2017-03-20 17:39:33
【问题描述】:

我有一个来自服务器的对象,我想在ionic2typescript读取这个。

我的问题:

我如何读取这个对象以获得每个键的值?

Example:

ionic 带有 标题 的列表: 在这种情况下,Header = key1 , key2 , key3value 是每个 keyvalues

Header = key1
items1
items1
items1
Header2 = key2
items2
items2
items2..

对象:

{
    "status": "success",
    "products": {
        "Key1": [
            {
              "entity_id": "448",
              "sku": "587",
              "name": "name",
              "image_url": "587.png",
              "price": "15,000",
              "qty": 0,
              "rating": 0,
              "wishlist": false,
              "specialprice": "7,500",
              "brand": "brandname"
            }
        ],
        "Key2": [
            {
              "entity_id": "448",
              "sku": "587",
              "name": "name",
              "image_url": "587.png",
              "price": "15,000",
              "qty": 0,
              "rating": 0,
              "wishlist": false,
              "specialprice": "7,500",
              "brand": "brandname"
            }
        ],
        "Key3": [
            {
              "entity_id": "448",
              "sku": "587",
              "name": "name",
              "image_url": "587.png",
              "price": "15,000",
              "qty": 0,
              "rating": 0,
              "wishlist": false,
              "specialprice": "7,500",
              "brand": "brandname"
            }
        ],
    }
}

【问题讨论】:

    标签: arrays json angular ionic-framework ionic2


    【解决方案1】:

    要在*ngFor循环中打印"Key"数组,先写一个Pipes

    Pipe.ts

    import { Component,Pipe, PipeTransform, Injectable } from '@angular/core';
    
    @Pipe({
      name: 'objectValues'
    })
    
    @Injectable()
    export class ObjectValuesPipe implements PipeTransform {
      transform(obj: any) {
        let result = [];
        for (var key in obj) {
          if (obj.hasOwnProperty(key)) {
            result.push(obj[key]);
          }
        }
        return result;
      }
    }
    

    别忘了在@NgModule 中导入你的Pipes,这样你就可以使用这个管道了。

    <ul *ngFor="let item of items">
       <li *ngFor="let value of item | objectValues">
         {{ value }}
       </li>
     </ul>
    

    基于:How to display json object using *ngFor and access key,value of object

    【讨论】:

      猜你喜欢
      • 2018-05-04
      • 1970-01-01
      • 1970-01-01
      • 2018-05-11
      • 1970-01-01
      • 2018-04-10
      • 2017-01-16
      • 2016-06-26
      • 2017-03-08
      相关资源
      最近更新 更多