Angular 2 not updating until any object is clicked

So it turns out that the sobotService was returning a q.js promise and not an ES6 promise. I believe this is probably why it didn't update as I'd expect it to like it did in the Heroes Tutorial.

By forcing it to update in the zone eg:

  this.sobotService .getRobots().then(ODataRobots => {
      this.zone.run(() => this.sobots = ODataRobots.data);          
  });

It managed to update the view as soon as the promise resolved.

I'll probably have to figure out if there is an easy way to remove the q.js promise from the library I am using (o.js) but in the meantime this works as expected!


Solution

As Abdul waheed mentioned before, the code that modifies the state needs to be wrapped with the ngZone service:

  // `ngZone` is the instance of the `NgZone` service.
  this.ngZone.run(() => {
    this.myState = 'new value';
  });

But as Madhur Bhaiya pointed out it is not detailed enough, so here I'm explaining a bit more.

Larger example

This example is provided by José Pedro Silva at GitHub Angular issues page.

public constructor(private ngZone: NgZone) {
}

public async update() {
  try {
    this.viewVariable = null;
    let newValue = await this.dataService.getAsync();

    this.ngZone.run(() => {
      this.viewVariable = newValue;
    });
  }
  catch (error) {
    this.viewVariable = error;
  }
}

Explanation

When there's an Asynchronous code (outside Angular scope) modifying the State, it will not trigger a View update. The click will do it. The NgZone Service can fix this issue.

The technique is helpful for AJAX calls as well as for any asynchronous call, such as an external library callback (which was my case).