【问题标题】:error display in *ngfor json array object*ngfor json 数组对象中的错误显示
【发布时间】:2016-08-18 18:20:45
【问题描述】:

从rest api获取json数组对象并尝试在ngfor中显示失败,原因是

错误

异常:找不到“object”类型的不同支持对象“[object Object]”。 NgFor 仅支持绑定到 Iterables,例如 Arrays。在 [HomeComponent@5:37 中的索引]

代码

import {Component} from 'angular2/core';
import {HomeService} from './home.services';
import {Index} from './index';

@Component({
    selector: 'home-app',
    providers: [HomeService],

    template: `
        <section class="left_side">
            <article>
                <div class="div_home">
                    <div class="div_homeIndxPartition">
                        <div class="div_IndxPartition" *ngFor="#indObj of indexes">
                            <table width="500px" class="idx_cons_table_det">
                                <tr>
                                    <th align="center" color="#A9F5F2"><h3>{{indObj.name}} ({{indObj.tracker}})</h3></th>
                                    <th align="center">Value</th>
                                    <th align="center">Change</th>
                                    <th align="center">%</th>
                                </tr>
                                <tr>
                                    <td align="center" colspan="1"></td>
                                    <td align="center">{{indObj.value}}</td>
                                    <td align="center">{{indObj.change}}</td>
                                    <td align="center">{{indObj.percent}}%</td>
                                </tr>
                            </table>
                            <br/>
                            <table width="500px" class="idx_cons_table">
                                <tr>
                                    <th align="center">High</th>
                                    <th align="center">Low</th>
                                    <th align="center">Open</th>
                                    <th align="center">Close</th>
                                    <th align="center">52 Week High</th>
                                    <th align="center">52 Week Low</th>                             
                                </tr>
                                <tr>
                                    <td align="center">{{indObj.high}}</td>
                                    <td align="center">{{indObj.low}}</td>
                                    <td align="center">{{indObj.open}}%</td>
                                    <td align="center">{{indObj.close}}</td>
                                    <td align="center">{{indObj.yearHigh}}</td>
                                    <td align="center">{{indObj.yearLow}}%</td>
                                </tr>
                            </table>                        
                        </div>                      
                    </div>
                </div>
            </article>
        </section>
    `

})
export class HomeComponent {
    public indexes:Array<Index>=[];
    public error;

constructor(private _service: HomeService){
    this.indexes = _service.getIndexes().subscribe(
            data => this.indexes =  JSON.parse(data),
            error => alert(" Error is : " + error),
            ()=> console.log("finished")
         );
    console.log(this.indexes);
}
}

JSON 数据

[
  {
    "id": 1,
    "name": "FTSE 100",
    "ticker": "UKX",
    "value": 69875.23,
    "change": 100,
    "percent": 2.3,
    "high": 69875.23,
    "low": 69700.89,
    "yearHigh": 699999.23,
    "yearLow": 680005.23,
    "open": 69600.54,
    "close": 699000.97,
    "constituents": null,
    "runDate": "21/04/2015"
  },
  {
    "id": 2,
    "name": "FTSE 250",
    "ticker": "MCX",
    "value": 465820.85,
    "change": 100,
    "percent": 2.3,
    "high": 465880.12,
    "low": 465810.74,
    "yearHigh": 478990.34,
    "yearLow": 465320.23,
    "open": 69600.54,
    "close": 699000.97,
    "constituents": null,
    "runDate": "21/04/2015"
  },
  {
    "id": 3,
    "name": "FTSE All-Share",
    "ticker": "ASX",
    "value": 236549.23,
    "change": 100,
    "percent": 2.3,
    "high": 236949.23,
    "low": 236149,
    "yearHigh": 246949.21,
    "yearLow": 235549.29,
    "open": 236519.23,
    "close": 236649.23,
    "constituents": null,
    "runDate": "21/04/2015"
  },
  {
    "id": 4,
    "name": "Euro Stoxx 50",
    "ticker": "STOXX50E",
    "value": 123469.87,
    "change": 100,
    "percent": 2.3,
    "high": 123499.87,
    "low": 123439.87,
    "yearHigh": 123499.87,
    "yearLow": 123169.87,
    "open": 123465.87,
    "close": 123459.87,
    "constituents": null,
    "runDate": "21/04/2015"
  },
  {
    "id": 5,
    "name": "S&P 500 ",
    "ticker": "S500",
    "value": 358976.36,
    "change": 100,
    "percent": 2.3,
    "high": 358986.36,
    "low": 358946.36,
    "yearHigh": 359976.36,
    "yearLow": 357976.36,
    "open": 358970.36,
    "close": 358996.36,
    "constituents": null,
    "runDate": "21/04/2015"
  },
  {
    "id": 6,
    "name": "Dow Jones I.A.",
    "ticker": "INDU",
    "value": 456789.36,
    "change": 100,
    "percent": 2.3,
    "high": 456799.36,
    "low": 456779.36,
    "yearHigh": 456889.36,
    "yearLow": 456689.36,
    "open": 456729.36,
    "close": 456779.36,
    "constituents": null,
    "runDate": "21/04/2015"
  },
  {
    "id": 7,
    "name": "GOLD",
    "ticker": "",
    "value": 500,
    "change": 100,
    "percent": 2.3,
    "high": 700,
    "low": 300,
    "yearHigh": 1500,
    "yearLow": 350,
    "open": 450,
    "close": 470,
    "constituents": null,
    "runDate": "21/04/2015"
  },
  {
    "id": 8,
    "name": "Brent Crude",
    "ticker": "",
    "value": 112,
    "change": 100,
    "percent": 2.3,
    "high": 115,
    "low": 107,
    "yearHigh": 200,
    "yearLow": 72,
    "open": 110,
    "close": 115,
    "constituents": null,
    "runDate": "21/04/2015"
  }
]

【问题讨论】:

  • 使用data.json() 代替手动解析。

标签: json angular ngfor


【解决方案1】:

我认为您在indexes 属性中设置的值不是数组而是对象。

我会看到几个原因:

  • 您从getIndexes 方法收到响应而不是有效负载。在这种情况下,您可以在此方法中使用 map 运算符:

    getIndexes() {
      return this.http.get(...).map(res => res.json());
    }
    
  • 接收到的负载不对应于数组,而是对应于它的一些属性。在这种情况下,您需要将此属性设置为indexes 属性。

如果你想遍历一个对象的属性,你需要像这样实现一个自定义过滤器:

@Pipe({name: 'keyValues'})
export class KeysPipe implements PipeTransform {
  transform(value, args:string[]) : any {
    let keys = [];
    for (let key in value) {
      keys.push({key: key, value: value[key]);
    }
    return keys;
  }
}

并像这样使用它:

<div class="div_IndxPartition" *ngFor="#indObj of indexes | keyValues">
  (...)
</div>

看到这个问题:

【讨论】:

  • 感谢您的回复。我正在获取 json 数组,我认为它将通过反射转换回域对象?我的理解错了吗?
  • 使用“response.json()”将文本响应负载解析为 json。对应的对象将是一个对象...
  • 什么是“数据”?你是怎么得到它的?
  • this.indexes = _service.getIndexes().subscribe(data => this.indexes = JSON.parse(data), error => alert(" Error is : " + error), () => console.log("完成") ); data 是我上次在问题中发布的来自服务器的 json 数据。
  • 我感到困惑的是,如果您设置了您分配的属性类型,我们无法将域对象显示为 *NG 中的数组,并且 json 到域对象将不会通过反射完成。
【解决方案2】:

我遇到了同样的问题,我的解决方案是没有 Pipes。我没有在返回观察者的模板中使用变量,创建中间变量并将结果分配给它。例如,我们将流保存到this.sub,但结果将在成功回调时保存到this.indexes,并将在html模板中使用此变量。

@Component({
  template: `
<ul>
  <li *ngFor="let index of indexs">
    {{ index }}
  </li>
</ul>
`
})
export class HomeComponent {
  privat sub;
  public indexes:Array<Index>=[];
  public error;

  constructor(private _service: HomeService) {
    this.sub = this._service.getIndexes().subscribe(
        data => this.indexes =  JSON.parse(data),
        error => alert(" Error is : " + error),
        () => console.log("finished")
     );

  }
}

【讨论】:

    【解决方案3】:

    你应该试试这个:

    在 html 中:

    <div  *ngFor="let subsciption of subscriptions;">
                         <div class="col-md-6">
                            <h5 class="widget-title">{{subsciption.name}}</h5>
                        </div>
    </div>
    

    在 .ts 文件中:

        export class SubscriptionComponent implements OnInit {
            private subscriptions: any =[]; 
            // private subscriptions: any ={};    // here dont use {}
        .
        .
        .
        .
        .
    
            getAllSubscriptions(queryString) {
                this._http.get(`${environment.base_url}/subscriptions` + queryString)
                    .subscribe((response: Response) => {
                        this.subscriptions = response.json();
                    },
    
                    (error: Response) => {
                        console.log("Login error");
                    });
            }
            this.getAllSubscriptions(query);
    
        }
    

    【讨论】:

      【解决方案4】:

      您不想在使用 Observables 时使用管道。 这个错误非常普遍,最好的方法是抛出一个 console.log() 看看你哪里出错了,因为它可能有很多东西。

      我的问题是我的数组在对象内部,我试图循环对象。其他问题可能包括映射或 ngFor。我的控制台输出看起来像这样:

      this.indexes = _service.getIndexes()
               .subscribe(
                  data => {
                      this.indexes = JSON.parse(data);
                      console.log(indexes);
                  },
                  error => alert(" Error is : " + error),
                      ()=> console.log("finished")
               );
          console.log(this.indexes);
      

      所以我需要的修复是这样的:

      this.indexes = _service.getIndexes()
                   .subscribe(
                      data => {
                          this.myNewObject = JSON.parse(data);
                          this.indexes = this.myNewObject.indexes;
                      },
                      error => alert(" Error is : " + error),
                          ()=> console.log("finished")
                   );
              console.log(this.indexes);
      

      这是因为数组嵌套在 Object 中,所以我只是创建了一个新对象,并通过获取它的属性来访问该数组。

      【讨论】:

        【解决方案5】:

        我看到了你的答案,简单的解决方法就是将 *ngFor 中的对象类型设置为这样的数组:

        public indexes:Array<TYPE_OF_YOUR_DATA>=[];
        

        【讨论】:

          猜你喜欢
          • 2021-03-28
          • 2018-08-13
          • 1970-01-01
          • 2022-07-07
          • 1970-01-01
          • 2017-12-13
          • 2017-07-24
          • 2016-06-09
          • 2022-11-13
          相关资源
          最近更新 更多