[英]reverse an observable array in angularfire2 angular 6
I am using a Observable array for real time data coming.我正在使用一个 Observable 数组来获取实时数据。 The data comes in ascending order, but I need it to display in reverse order.
数据按升序排列,但我需要它以相反的顺序显示。 Examples on inte.net are before angular 5 and the syntax no longer works.
inte.net 上的示例在 angular 5 之前,语法不再有效。 Please advise
请指教
html html
<tr *ngFor="let card of cards | async;let last = last ">
<td> <img [src]="card.frontImageUrl" width=200 height="100"></td>
</td>
refreshCards(){
this.cards = this.dataSvc.fetchCards().pipe(
map((cards: any) => cards.map(cardObj => new Card(cardObj.key, cardObj._frontImageUrl, cardObj._backImageUrl, cardObj._status, cardObj._date, cardObj._userId, cardObj._message)))
);
}
call to firedb调用 firedb
fetchCards(){
this.cardList = this.db.list<Card>('adminCardQueue', ref => ref.orderByChild('_date').limitToLast(50))
return this.cardList.snapshotChanges().pipe(
map(changes =>
changes.map(c => ({ key: c.payload.key, ...c.payload.val()}))
)
) ;
}
You can reverse the array at *ngFor using.slice().reverse()您可以在 *ngFor 使用 .slice().reverse() 反转数组
<tr *ngFor="let card of (cards | async)?.slice().reverse();let last = last ">
The .slice() creates a copy of the array and the .reverse() does the reverse action on your array. .slice()创建数组的副本,而.reverse()对您的数组执行反向操作。
you can use ---您可以使用 - -
*ngFor="let item of items.slice().reverse()"
Reversing an Observable or an Array inside template is possible but not recommended at all .在模板中反转 Observable 或 Array 是可能的,但根本不推荐。 Do not bring any sort of
JavaScript function's logic
inside html template.不要在 html 模板中引入任何类型的
JavaScript function's logic
。
WHY为什么
1- It will work in development
but in production
it will not reverse the array. 1-它会在
development
中工作,但在production
中它不会反转数组。
2- It is the incorrect use of Angular Framework. 2-这是 Angular 框架的错误使用。 As you are
mutating
an array inside of change detection cycle
.当您在
change detection cycle
内mutating
数组时。
Refrence https://github.com/angular/angular/issues/34131参考https ://github.com/angular/angular/issues/34131
Solution You should reverse your array inside Ts
.解决方案您应该在
Ts
中反转数组。
refreshCards(){
this.cards = this.dataSvc.fetchCards().pipe(
map((cards: any) => cards.map(cardObj => new Card(cardObj.key, cardObj._frontImageUrl, cardObj._backImageUrl,
cardObj._status, cardObj._date, cardObj._userId, cardObj._message).slice().reverse())
);
}
ZOOMED new Card()
放大
new Card()
new Card(cardObj.key, cardObj._frontImageUrl, cardObj._backImageUrl,
cardObj._status, cardObj._date, cardObj._userId, cardObj._message).slice().reverse()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.