Angular2多维数组ng-for not working

时间:2015-10-25 21:57:57

标签: javascript arrays angular

我使用的是Angular2,一切正常,但无法打印出多维数组,这里是代码:

<root field="4">
<a>
    <aa x="1"/>
    <ab>
        <aba number="36" usefulness="useful">
            <abaa>text1</abaa>
            <abab>
                <ababa>text2</ababa>
            </abab>
        </aba>
        <abb number="37" usefulness="useful">
            <abba>text3</abba>
            <abbb>
                <abbba>text4</abbba>
                <abbbb>text5</abbbb>
            </abbb>
        </abb>
    </ab>
</a>
</root>

简单的非多维数组的第一个例子按预期工作

<root strahler="2" field="4">
<a strahler="2">
    <aa strahler="0" x="1"/>
    <ab strahler="2">
        <aba strahler="1" number="36" usefulness="useful">
            <abaa strahler="0">text1</abaa>
            <abab strahler="0">
                <ababa strahler="0">text2</ababa>
            </abab>
        </aba>
        <abb strahler="1" number="37" usefulness="useful">
            <abba strahler="0">text3</abba>
            <abbb strahler="1">
                <abbba strahler="0">text4</abbba>
                <abbbb strahler="0">text5</abbbb>
            </abbb>
        </abb>
    </ab>
</a>
</root>

发出错误但不起作用的问题:

var imgSrc = document.getElementsByClass("efImage").src;

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

我找到了解决方案,你需要在循环之前将对象转换为数组:

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

这是管道:

[{
    "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>

1 个答案:

答案 0 :(得分:0)

根据相关更新,您需要先将对象转换为数组,然后再遍历它:

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

使用的管道如下:

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;
  }
}