【问题标题】:Angular 2 getting json data with ngfor [duplicate]Angular 2使用ngfor获取json数据[重复]
【发布时间】:2018-12-19 03:10:21
【问题描述】:

我在 URL 中有一个 JSON 数组,我正在尝试从中获取信息,以便可以在 ngFor 中使用它。如果我想获取链接或名称并在ngFor 中使用它,我做错了什么?因为我在console.log(this.straip) 中得到它,但不能在ngFor 中使用它。

Component.ts

export interface straipsnelis {
  name: string;
  link: string;
}

straip = {} as straipsnelis;
ngOnInit() {
  this.http.get('this.url').subscribe((data:any) => {
    this.straip.link = data.map((a:any)=>a.guid);
    this.straip.name = data.map((a:any)=>a.slug);
    console.log(this.straip);
  })
}

HTML

<div *ngFor="let s of straip" class="cardukas">
  <div class="left-photo">{{s.link}}</div>
  <div class="right-info"></div>
</div>

控制台错误:

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

【问题讨论】:

  • 请提供控制台结果
  • straip 不是对象数组。
  • 如何转换成对象数组?
  • {链接:数组(2),名称:数组(2)}链接:数组(2)0:{渲染:“life.optomeda.lt/?p=168”} 1:{渲染:“life.optomeda.lt/?p=1” } 长度:2 proto:数组(0)名称:数组(2)0:“h1-post-name-lorem-ipsum-dolor-sit-amet-consectetur-adipiscing-elit”1: “pirmasis-tinklarascio-irasas”长度:2 proto:Array(0) proto:Object
  • Angular 不能循环一个Object,ngFor只支持iterables,你需要提供一个数组。

标签: javascript angular typescript angular-http


【解决方案1】:

ngFor 不迭代对象,它只迭代数组。

TS:

export interface straipsnelis {
  name: string;
  link: string;
}

straip = {} as straipsnelis;

straipArray : Array<any> = []; 

ngOnInit() {
  this.http.get('this.url').subscribe((data:any) => {
    this.straip.link = data.map((a:any)=>a.guid);
    this.straip.name = data.map((a:any)=>a.slug);
    this.straipArray.push(this.straip)

    console.log(this.straip);
  })
}

HTML:

<div *ngFor="let s of straipArray" class="cardukas">
  <div class="left-photo">{{s.link}}</div>
  <div class="right-info"></div>
</div>

【讨论】:

  • 我在 html 中得到 [object object]。现在没有控制台错误。
猜你喜欢
  • 2017-07-01
  • 1970-01-01
  • 2016-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 2018-11-16
相关资源
最近更新 更多