是否有可能在 angular 中绑定数组

Is there is any possibilty for binding array in angular

服务模块:

  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>

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

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

listItems = [];

由于错误指示 *ngFor 只能像数组一样遍历可迭代对象。然而你的 API returns 一个对象。理想情况下,任何数据转换都必须在后端完成。但是,如果您愿意,前端有以下选项。

选项 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>