【问题标题】:Is there is any possibilty for binding array in angular有没有可能以角度绑定数组
【发布时间】:2021-08-18 05:49:52
【问题描述】:

服务模块:

  baseurl: string = 'https://fireman-7cc06-default-rtdb.firebaseio.com/'

  getFunction(): Observable<object> {
    return this.http.get(this.baseurl + 'items.json')
  }

组件模块:

 ngOnInit(): void {

    this.itemservices.getFunction().subscribe(data => {
      this.listItems= data
     
      console.log(this.listItems)
      
    }, err => {
      console.log('error' + err)
    })
  }

查看:

<div *ngIf="listItems">
    <ul *ngFor="let info of listItems">
        <li>{{info.Item_name}}</li>
       
    </ul>
</div>

【问题讨论】:

  • 你想要达到什么目的?您想在 HTML 中显示 listItems 数组项吗?
  • 实际上我得到了类似=> core.js:6456 ERROR 错误:找不到类型为“object”的不同支持对象“[object Object]”。 NgFor 只支持绑定到 Arrays 等 Iterables。
  • 您的 API 未返回数组
  • 您可以使用“Object.entries(object)”将对象转换为数组
  • 非常感谢,,,,成功了!!!

标签: arrays angular ngfor


【解决方案1】:

由于错误表明*ngFor 只能像数组一样循环遍历可迭代对象。但是,您的 API 返回一个对象。理想情况下,任何数据转换都必须在后端完成。但是,如果您愿意,您可以在前端使用以下选项。

选项1:将对象转换为数组

您可以使用 JS Object.values() 和 RxJS map 运算符来获取对象的值作为数组。

const input = {"-MhJ49AIHh-53nnF07a1":{"Item_color":"white","Item_name":"amma","Item_price":"369","Item_type":"human"},"-MhJXlVgPBdZ6Q7L0Tnn":{"Item_color":"red","Item_name":"manu","Item_price":"1000","Item_type":"sunny"},"-MhJa9Xzmdq9OvkZyVN7":{"Item_color":"yellow","Item_name":"chinnu","Item_price":"500000","Item_type":"sunny"}}
console.log(Object.values(input))
.as-console-wrapper { max-height: 100% !important; top: 0; }
import { map } from 'rxjs/operators';

baseurl: string = 'https://fireman-7cc06-default-rtdb.firebaseio.com/'

getFunction(): Observable<object> {
  return this.http.get(this.baseurl + 'items.json').pipe(
    map((res: any) => Object.values(res))
  );
}

选项 2:使用 Angular keyvalue 管道

您可以跳过使用Object.values() 的转换并使用组件模板中的keyvalue 管道来迭代对象。

服务

baseurl: string = 'https://fireman-7cc06-default-rtdb.firebaseio.com/'

getFunction(): Observable<object> {
  return this.http.get(this.baseurl + 'items.json')
}

模板 (*.html)

<div *ngIf="listItems">
  <ul *ngFor="let info of listItems | keyvalue">
    <li>{{info?.value?.Item_name}}</li>
  </ul>
</div>

【讨论】:

    【解决方案2】:

    这里的问题是你试图循环一个对象而不是数组。请检查您如何定义 this.listItems。

    将其声明为数组并相应地分配值。然后你应该能够在html代码中循环。

    listItems = [];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-06
      • 2021-05-16
      • 1970-01-01
      • 2016-12-04
      • 2012-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多