0

I am writing an app with Ionic 2 and am making good progress, but I just got hung up on something that I think is probably a simple fix.

I have text on the screen, after 5 seconds I want to update the text on the screen. I seem to lose access to the variable within the setInterval function.

constructor(public nav: NavController, private navParams: NavParams, private getserver: GetServerService, storage: Storage) {
    this.storage = storage;

    this.storage.get('userAuth').then((name) => {
      if(name.id === undefined) {
          this.nav.setRoot(LoginPage);  //kick back to login if no userdata
      }else{

          let options = {timeout: 120000, enableHighAccuracy: true};
          navigator.geolocation.getCurrentPosition((position) => {

            this.driverStatus = 'hi';  

            setInterval(()=> {
                this.driverStatus = 'Updated Text';
            }, 2000);

          },
          (error) => {
            console.log(error);
          },
          options
        );  
      }
    }); 

  }

}

When I run the app, it shows the text "Hello" but never updates the text to "Updated Text". The console shows the output properly.

I have tried suggestions from Ionic2 function setInterval can't get a parameter but those suggestions did not work either. My other failed attempts are below.

var that = this;
setInterval(function() {
   that.userText = 'Updated Text';
}, 2000);

and

setInterval(()=> {
    this.userText = 'Updated Text';
}, 2000);
Developer Gee
  • 362
  • 3
  • 12

2 Answers2

0

This is something about the Zones from Angular 2. This has been discussed here You can fix it by injecting an NgZone's object and calling its run() method

setInterval(()=> {
   this.ngZone.run(() => {
      this.userText = 'Updated Text';
   });
}, 2000);
Christian Benseler
  • 7,907
  • 8
  • 40
  • 71
  • Thanks for the response. I think I have to include another file in order for ngZone to work. It didn't run out of the box. I realized that I already had the gps coordinates I needed available on the previous window (to generate a map), so I just stored those and carried them over to this page, which negated my problem. It sped the app up a little bit that way too. – Developer Gee May 30 '17 at 13:35
  • You have to mport it in your component and then inject it in the constructor. – Christian Benseler May 30 '17 at 13:37
0

Instead of using NgZone, you can simple bind this as follow:

    setInterval(function () {
        that.userText = 'Updated Text';
    }.bind(this), 1000);
Pierre
  • 1,044
  • 15
  • 27