【问题标题】:Access HTTP nested JSON data in Angular在 Angular 中访问 HTTP 嵌套的 JSON 数据
【发布时间】:2017-08-30 12:13:56
【问题描述】:

这是有问题的组件:

@Component({
  selector: 'my-app',
  template: `
  {{tests | json}}

    <div *ngFor='let test of tests'>
        <div *ngFor='let x of test.A.B'>
          <div *ngFor='let y of x.C.D'>
            writerid:{{y.writerid}} <br>
            content:{{y.content}} <br>
            writedt:{{y.writedt }} <br>
          </div>
       </div>
    </div>
  `,
})

public tests: any[];

构造函数在这里从 API 获取 JSON 数据:

constructor(private _http: Http) {
    _http.get(this.API_URI).subscribe(result => {
      this.tests = result.json();
    });
  }

这是我来自http(API_URI) 的 JSON 数据,由{{tests | json}} 打印(在@component,模板中):

 {
   'A': {
     'B': [{
       'C': {
         'D': [{
           'content': 'content_test1',
           'writedt': '2017-02-08 00:00:00',
           'writerid': 'writerid_test1'
          }, {
           'content': 'content_test2',
           'writedt': '2017-02-08 00:00:00',
           'writerid': 'writerid_test1'
          }, {
            'content': 'content_test3',
            'writedt': '2017-02-08 00:00:00',
            'writerid': 'writerid_test2'
          },  {
           'content': 'content_test4',
           'writedt': '2017-02-08 00:00:00',
           'writerid': 'writerid_test2'
         }]
       }
     }]
   }
 }

我得到的错误是这样的:

找不到“object”类型的不同支持对象“[object Object]”。 NgFor 只支持绑定到 Arrays 等 Iterables。

我该如何解决?

【问题讨论】:

  • 让我们从公然开始:JSON 格式的tests 是 JSON object,而不是 JSON array,这就是为什么你可以'迭代它。

标签: json angular


【解决方案1】:

查看您的 json,它有对象,但 ngFor 适用于数组类型

<div *ngFor='let x of tests.A.B'>
          <div *ngFor='let y of x.C.D'>
            writerid:{{y.writerid}} <br>
            content:{{y.content}} <br>
            writedt:{{y.writedt }} <br>
          </div>
       </div>
    </div>

这就是您收到此错误的原因。

错误

  1. &lt;div *ngFor='let test of tests'&gt; - 测试是对象类型,而不是对象或数组的集合。

LIVE DEMO

【讨论】:

  • 它适用于本地 json 数据,但是当我从 http 像构造函数(私有 _http: Http){ _http.get(this.API_URI).subscribe(result => { this.tests = result .json(); });错误类型错误:无法读取未定义的属性“_source”
  • 你能用我的demo plunker并用json文件创建http调用吗
  • 这是我真正的 json 数据它仍然无法正常工作 TT 错误类型错误:无法读取未定义的属性“命中”
  • { "hits": { "hits": [{ "_source": { "json_cmets": [{ "content": "\u314b\u314b\u314b\u314b - DCW", "writedt ": "2016-02-08 17:05:48", "writerid": "morefico3042" }, { "内容": "\uc800\ubc88\uc5d0 \ub3d9\uc7a5A\uc758 \ubcbd\uc744 \uc2e4\uac10 \ud558\uc2dc\uace0\ub3c4\ub3c4\uc804\ud558\uc2dc\ub294? \u3161\u3161", "writedt": "2016-02-08 17:07:38", "writerid": "\uce74\ ub77c\ube71" }] } }] } }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-25
  • 1970-01-01
相关资源
最近更新 更多