使用angular-2读取[object object],

时间:2018-01-09 07:37:48

标签: angular ionic-framework

我试图在我的应用程序中读取json文件,但它只显示我:“[object object]”。在控制台中我可以看到它,它映射到我的json文件。但输出窗口只显示“[对象对象]“如下图所示。

这里是home.html

 <ion-header>
  <ion-navbar>
    <ion-title>
     Home
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
 <ion-card #myCard  *ngFor="let item of quotes.data">

  <ion-card-content>
    <ion-card-title>
    {{item.categories}}
    </ion-card-title>
    <p>
      {{item.menuItems}}
    </p>
  </ion-card-content>
 </ion-card>
</ion-content>

输出图像在这里

output image is here

我的json文件

{

    "categories" : {
      "101flashlight" : {
        "desc" : "Crackers with multiple sounds",
        "thumb" : "infw/thumb/flash.svg",
        "title" : "Flash Light "
      },
      "102zamin" : {
        "desc" : "Crackers with sparks",
        "thumb" : "infw/thumb/zamin.svg",
        "title" : "Zamin Chakkars"
          }
}

服务文件quote.ts

import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
@Injectable()
export class QuoteService{
    public data:any;
    private http:any;

constructor(http:Http){
    this.http=http;

}
getQuotes(){
    this.http.get("assets/data.json")
    .subscribe(res =>{
        this.data=res.json();
        this.data=Array.of(this.data);
        console.log(this.data);
    }, error =>{
        console.log(error);

    });
}
}

我想要显示标题,desc和拇指

1 个答案:

答案 0 :(得分:0)

您的类别必须是可迭代的对象。目前,您有一个JSON对象,而Angular无法迭代Object的属性。

如果您可以更改JSON文件格式,则可能有所帮助:

{
    "categories": [
        {
            "desc": "Crackers with multiple sounds",
            "thumb": "infw/thumb/flash.svg",
            "title": "Flash Light ",
            "cat": "101flashlight"
        },
        {
            "desc": "Crackers with sparks",
            "thumb": "infw/thumb/zamin.svg",
            "title": "Zamin Chakkars",
            "cat": "102zamin"
        }
    ]
}

如果需要遍历Object,可以查看Object#values方法,看看它是否有帮助: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values