简体   繁体   English

angular2如何迭代对象数组

[英]angular2 how to iterate array of objects

I want to iterate an array of objects but I received the following error: 我想迭代对象的数组,但收到以下错误:

inline template:25:9 caused by: Cannot read property 'length' of null

The followings are parts of my code: 以下是我的代码的一部分:

// Definition of the array
public columnsConfig: Array<ColumnConfig>;

where ColumnConfig is a class of all the instances included in the array. 其中, ColumnConfig是数组中包含的所有实例的类。

// Constructor of the component
this.columnsConfig = new Array<ColumnConfig>();


// Function that builds the array to iterate
for(var columnName in _headers) {
  let config = new ColumnConfig(columnName, _headers[columnName]);`
   this.columnsConfig.push(config);`           
}   

Template: 模板:

<th *ngFor="let config of columnsConfig">

What am I missing here? 我在这里想念什么?

You can use RX js map operator to iterate and make an Array of values. 您可以使用RX js映射运算符来迭代并生成值数组。

import { Component, OnInit } from '@angular/core';
import 'rxjs/add/operator/map';

@Component( {
  selector: 'app-root',
  template:
  `<ol>
    <li *ngFor="let config of columnsConfig ">
    {{config}}
   </li>
   </ol>`
} )
export class AppComponent
{
  ngOnInit() { this.make() }

  public columnsConfig: any[]
  public _headers: any =
  [
    { columnName: 'one', otherName: 'foo' },
    { columnName: 'two', otherName: 'boo' },
    { columnName: 'three', otherName: 'loo' }
  ];

  make()
  {
    let config = [];
    this._headers
      .map( x =>
      {
        config.push( x.columnName );

        this.columnsConfig = config;

        console.log( 'progress: ', config );
      } )
    console.log( 'final result: ', this.columnsConfig );
  }
}

I found the problem: it was related to a default value of a string variable defined in the object that composes the array. 我发现了问题:它与组成数组的对象中定义的字符串变量的默认值有关。 So, I changed the default variable to an empty string ('') and it worked. 因此,我将默认变量更改为空字符串(''),并且可以正常工作。

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

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