简体   繁体   English

Angular2 多维数组 ng-for 不起作用

[英]Angular2 Multidimensional array ng-for not working

I am using Angular2, all working good, but am unable to printout multidimensional arrays, here is the code:我正在使用 Angular2,一切正常,但无法打印多维数组,这是代码:

class AppComponent {
    items:Array<Object>;
    constructor(http: Http) {
    http.get('data.json')
      .map(res => res.json())
      .subscribe(data => this.items = data);
  }
}

First example with simple non-multidimensional array works as expected第一个带有简单非多维数组的示例按预期工作

[{
    "id": "1",
    "v2": "L'Oréal Paris",
    "v4": "Serum Absolute Advanced Age-Reversing Makeup"
}]

<div *ng-for="#item of items">
    {{item.v2}} {{item.v4}}
</div>

Problem that emits error and does not work:发出错误且不起作用的问题:

[{
    "4940": {
        "id": "4940",
        "v2": "Pantene Pro-V",
        "v4": "Cleansing Conditioner"
},
    "4941": {
        "id": "4941",
        "v2": "Pantene Pro-V",
        "v4": "Conditioner"
},
    "4942": {
        "id": "4942",
        "v2": "Pantene Pro-V",
        "v4": "2in1 Shampoo and Conditioner"
}]


<div *ng-for="#item of items">
  <div *ng-for="#itemone of item">
    {{itemone.v2}} {{itemone.v4}}
  </div>
</div>

+++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++++++++++++++++++++++++

I've found a solution, you need to convert object to array before loop:我找到了一个解决方案,您需要在循环之前将对象转换为数组:

<div *ng-for="#item of items">
  <div *ng-for="#itemone of item | objToArr">
    {{itemone.v2}} {{itemone.v4}}
  </div>
</div>

And here is the Pipe:这是管道:

import { Pipe } from 'angular2/angular2';

@Pipe({
  name: 'objToArr',
  pure: false
})
export class ObjToArr {
  transform(object:any) {
    var newArray = []
    for (var key in object) {
        newArray.push(object[key]);
    }
    return newArray;
  }
}

As per the update in question, you need to convert object to array before looping over it:根据相关更新,您需要在循环之前将对象转换为数组:

<div *ng-for="#item of items">
  <div *ng-for="#itemone of item | objToArr">
    {{itemone.v2}} {{itemone.v4}}
  </div>
</div>

The pipe used is below:使用的管道如下:

import { Pipe } from 'angular2/angular2';

@Pipe({
  name: 'objToArr',
  pure: false
})
export class ObjToArr {
  transform(object:any) {
    var newArray = []
    for (var key in object) {
        newArray.push(object[key]);
    }
    return newArray;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM