【问题标题】:How do I iterate in reverse with *ngFor directive?如何使用 *ngFor 指令反向迭代?
【发布时间】:2021-11-28 11:29:40
【问题描述】:

在 Angular 中,我正在尝试查询 Firebase,我希望当对象返回时,反向迭代内容。

在 TS 我得到了这个

 this.items = db.list('/items', ref => ref.limitToLast(10)).valueChanges();

我尝试在那里使用 reverse(),但是,我收到一条错误消息“可观察类型上不存在反向”

在 HTML 中我有这个

*ngFor="let item of items | async | slice:0:100"

我怎样才能做到这一点?

【问题讨论】:

  • *ngFor="let item of items.slice().reverse()" 试试这个。
  • 那行不通。似乎是最常见的解决方案,而且最不可能奏效。

标签: angular firebase firebase-realtime-database angularfire ngfor


【解决方案1】:

您可以使用 RxJS 运算符 map 和管道来转换最终发出的值:

this.items = db.list('/items', ref => ref.limitToLast(10)).valueChanges().pipe(map(values => values.reverse());

【讨论】:

    【解决方案2】:

    valueChanges() 返回一个包装底层数据数组的 Observable。为了反转底层数据数组,您可以通过map RxJS 运算符管道 Observable 并返回反转后的数组。

    this.items = db.list('/items', ref => ref.limitToLast(10)).valueChanges()
                         .pipe(
                         map(values => values.reverse())
                         );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-14
      • 2023-03-08
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      相关资源
      最近更新 更多