How to update the view after changing the database with IONIC 2

0

I'm developing an application with IONIC 2 where I use a webservice REST, of an application that is running online. In the page opening, I make the request and display information correctly on the screen, however, when an item is inserted or changed on the server, the view does not update, but when I exit and return to the page.

Some snippets of code being used:

Vision:

<span *ngFor="#item of depoimentos">{{item.nome)}}</span>

Controller class that initializes testimonials:

ngOnInit() {
this.service.findAll().subscribe(
  data => {
    this.depoimentos = data;
    console.log(this.depoimentos);
    if (this.depoimentos.length > 0) {
      this.depoimentos[0].visivel = true;
    }
  }
)}

Excerpt from service requesting:

findAll() {
    return this.http.get(depoimentosURL)
        .map(res => res.json())
        .catch(this.handleError);
}

Remembering: I'm using Ionic 2, which works with angle v2.0.0-beta.15

    
asked by anonymous 27.05.2016 / 19:18

1 answer

1

To make a page real-time you should use the timer function of an Observable to perform the refresh of the page.

For example, when starting the page we should call the function responsible for obtaining the service data:

private timerSubscription: AnonymousSubscription;
private depoimentosSubscription: AnonymousSubscription;

ngOnInit() {
    this.refreshServico(); // função para obter dados do serviço 
}

In the function that calls the service to get the desired data, you must call a function that will reload the data in a certain interval:

private refreshServico(): void {

       this.depoimentosSubscription = this.service.findAll().subscribe(
          data => {
            this.depoimentos = data;
            console.log(this.depoimentos);
            if (this.depoimentos.length > 0) {
              this.depoimentos[0].visivel = true;
            }
            this.subscribeDados();
          }
        );
}

And finally add the timer to call the service automatically after a certain period:

 private subscribeDados(): void {
    this.timerSubscription = Observable.timer(1000).first().subscribe(() => this.refreshServico()); 
}

Calling the refreshService () function for each successful event prevents multiple service calls from occurring when it takes longer than the time set in the timer (in the 1s example).

It is important to remember that you should remove the subscribe in the onDestroy () method to avoid memory leaks.

  public ngOnDestroy(): void {
    if (this.depoimentosSubscription) {
        this.depoimentosSubscription.unsubscribe();
    }
    if (this.timerSubscription) {
        this.timerSubscription.unsubscribe();
    }
}
    
08.02.2017 / 01:31