user14324857
user14324857

Reputation: 61

How to display a message when a new entry appears?

I have a request that get data from the server. And this request is executed every second. And let's say I want to send in console.log("New post") a message if a new entry appears. How do make it clear to the request that a new record has been added?

 ngOnInit() {
    this.load();
  }

  load() {
    this.ngUnsubscribe = timer(0, 1000).pipe(
      switchMap(() => this._orders.getAllOrders())
    ).subscribe(orders => {
      this.orders = orders
    }, error => {
      this._toast.error(error.error.message);
    })
  }

Upvotes: 0

Views: 54

Answers (1)

AlleXyS
AlleXyS

Reputation: 2598

Sorry for the comment. Before to assign the new value to your variable, check if are equals

  counter = 0;
  load() {
    this.ngUnsubscribe = timer(0, 1000).pipe(
      switchMap(() => this._orders.getAllOrders())
    ).subscribe(orders => {
      if(JSON.stringify(orders) !== JSON.stringify(this.orders)) {
        this.orders = orders;
        if (this.counter > 0) {
          console.log('new data');
        }
        this.counter++;
      }
    }, error => {
      this._toast.error(error.error.message);
    })
  }

to prevent to display the message for the first request, you can use a counter:

Upvotes: 1

Related Questions