首页  >  问答  >  正文

错误 NG0900 尝试比较时出错。仅允许数组和可迭代对象

使用 *ngFor 我能够渲染数据,但它会抛出此错误

错误 错误:NG0900:尝试比较“[object Object]”时出错。仅允许数组和可迭代对象

这是我的服务方法

async getEditions(): Promise<Observable<Cigales>> {
    return this.http.get<Cigales>(url+"/candidates/editions", httpOptions).pipe(
      tap((getEditions: Cigales) => this.log('getEditions' + getEditions)),
      catchError(this.handleError<Cigales>('getEditions'))
    );
  }

这是我的组件方法

editions: Cigale[] = [];

  async getEditions(): Promise<void> {
    await this.CigalesService.getEditions().then(res=> {
      res.subscribe(data => {
        this.editions = [];
        this.editions = data.content;
      })
    })
  }

这是我的 Cigales 界面

export interface Cigales {
  content: Array<Cigale>,
  pageable: pageable,
  last: string;
  totalPages: string;
  totalElements: string;
  size: string;
  number: string;
  sort: sort;
  first: string;
  numberOfElements: string;
  empty: string;
}

export interface Cigale {
  id?: string;
  eventName: string;
  eventStartDate: string;
  eventEndDate: string;
}

type sort = {
  empty: boolean,
  sorted: boolean,
  unsorted: boolean
}

type pageable = {
  sort: sort,
  offset: string;
  pageNumber: string;
  pageSize: string;
  paged: string;
  unpaged: string;
}

这是我的 component.html

<tr *ngFor="let item of editions">
        <td>{{item.eventName}}</td>
        <td>{{item.eventStartDate}}</td>
        <td>{{item.eventEndDate}}</td>
        <td>
          <a class="d-inline" role="button" data-bs-toggle="modal" data-bs-target="#application-modal"><i class="bi bi-clipboard"></i></a>
          <a class="d-inline" role="button" data-bs-toggle="modal" data-bs-target="#application-modal"><i class="bi bi-pencil-square"></i></a>
        </td>
      </tr>

Console.log(this.editions) 和我得到两个对象的数组

控制台结果

编辑:我尝试过 Array.isArray(this.editions) 并且它返回 true

P粉226667290P粉226667290236 天前403

全部回复(1)我来回复

  • P粉852578075

    P粉8525780752024-02-26 14:43:53

    首先,您面临的错误与您尝试使用对象而不是数组作为 *ngFor 指令的数据源有关。

    其次,尝试将数据分配给 this.editions,例如:

    async getEditions(): Promise {
      await this.CigalesService.getEditions().then(res=> {
        res.subscribe(data => {
          this.editions= [...data.content];
        })
      })
    }

    此外,我建议您避免在 Angular 应用程序中使用 Promise,而是通过利用订阅使代码更具反应性。

    回复
    0
  • 取消回复