【问题标题】:unable to display json content-Angular无法显示 json 内容-Angular
【发布时间】:2019-05-07 13:11:46
【问题描述】:

我是 Angular 的新手,想弄清楚如何读取和显示 json 文件的内容。

组件.ts

import { Component, OnInit } from '@angular/core';
import { RoomService } from '../shared/room.service';
@Component({
  selector: 'app-footer',
  templateUrl: './footer.component.html',
  styleUrls: ['./footer.component.css']
})
export class FooterComponent implements OnInit {
  public httpdata=[];
  constructor(private roomservice:RoomService) { 
  }

  ngOnInit() {
    this.roomservice.getJSON().subscribe(data => {
      this.httpdata.push=data;
      console.log(data);
  });
  }
}

.html

 <div>
      <ul *ngFor="let t of httpdata ">
      {{t.id |json}}
      </ul>

   </div>

我可以使用 console.log 获取数据,但无法显示数据。

我的 JSON:

  {
  "rooms":[
    {
      "id": "1",
      "name": "abd",
      "Description": "blah blah",
      "Settings": {
        "Sources": ["ass","fff"],
        "hex": "#000"
      }
    },
    {
      "id": "2",
      "name": "abc",
      "Description": "blah",
      "Settings": {
        "Sources": ["sss,ddd"],
        "hex": "#000"
      }
    }
  ]
}

任何帮助表示赞赏!

【问题讨论】:

  • 您当前的代码有很多问题。请问,你有没有试过在angular.io跟随英雄之旅?
  • 不,我在 stackover flow 上找到了这段代码,就像我说的那样,数据确实显示在控制台上。我只是无法显示它。不过会在 angular.io 上查看英雄,谢谢 :)

标签: angular data-binding rxjs ngfor


【解决方案1】:

您没有正确推送到数组,如下所示

this.httpdata.push(data);

如果这是您需要的,那应该正确填充您的数组,尽管我认为下面是提供的代码应该发生的事情。从订阅内部开始。

ngOnInit() {
  this.roomservice.getJSON().subscribe(data => {
      this.httpdata = data.rooms;
      console.log(this.httpdata);
  });
}

然后在模板中

<div>
  <ul *ngFor="let rooms of httpdata ">
    <li>{{ rooms.id }}</li>
  </ul>
</div>

阅读的好地方Angular tutorial

【讨论】:

  • 我尝试使用 this.httpdata.push(data);但它仍然没有显示任何内容。
  • 忽略第一位只是为了展示 .push() 的工作原理,它不是您需要的,从下面阅读,检查编辑:)
猜你喜欢
  • 2015-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-21
  • 2021-10-24
  • 2015-03-03
相关资源
最近更新 更多