0

I have a problem when I want to reverse my observable list after adding new item

I used this way to reverse it during first start

    import { Pipe, PipeTransform } from '@angular/core';

    @Pipe({
    name: 'reverse'
    })

    export class ReversePipe implements PipeTransform { 
      transform (value) {
        if(!value)return;
        return value.reverse();
      }
    }

In HTML

    <div *ngFor="let msg of (msgsList | async) | reverse">

But after adding any new item, the list shown as this picture [ List after adding ]

Also I checked this link [ https://stackoverflow.com/questions/40293539/is-it-possible-to-reverse-a-firebase-list ] but same results

raaaay
  • 496
  • 7
  • 14
Zero
  • 1
  • 2

1 Answers1

0

Assuming you have the same case as me and have the list in server-side and a copy in the angular front-end. You can use .push() to append to the list on the backend but use .unshift() on the client-side.

So every time you re-query the list from server you still make use of the | reverse but when you add to the list you .unshift() on the frontend list and send the ajax POST to server-side which uses .push().

If you only have client-side app I assume you can only use .unshift() and not use the reverse pipe.

How I used it:

Client side:

private messageStore = [];
private messageSubject = new Subject();
messages = this.messageSubject.asObservable();

//..

this.messageStore.unshift(newMessage);
this.messageSubject.next(this.messageStore);

//..

<div *ngFor="let message of (webService.messages | async) | reverse">

Then ajax Post to server and server does this:

messages.push(req.body);

And every time you refresh the page or load the entire message list from server you just set that as new client-side list.

this.messageStore = response.json();
this.messageSubject.next(this.messageStore);
Alvar
  • 11
  • 4