MatthewScarpino
MatthewScarpino

Reputation: 5936

Using Promises and Zones in Angular2

I'd like to display the result of processing a promise in a component's template. I've tried using zone.run, but that hasn't helped. Here's my component:

@Component({ selector: 'test' })
@View({ template:
`<div class="test">
  <p>Result: {{ result }}</p>
</div>`
})

export class Test {
  promise: Promise<string>;
  result: string;

  constructor(private _zone: NgZone) {

    // Process promise
    this._zone.run( function() {
      this.promise = new Promise(function(resolve, reject) { resolve("Hi there"); });
      this.promise.then(function(msg: string) { this.result = msg; });
    });
  }
}

When this runs, the template doesn't change. I tried putting zone.run inside the then method, but that gave an error. Any thoughts?

Upvotes: 3

Views: 16719

Answers (2)

Moe
Moe

Reputation: 63

If you would like to use a declared function:

...
this.promise.then(msg => this.doSomethig(msg));
}

doSomething(msg){
  this.msg = msg;
  //other stuff
}

Upvotes: 0

MatthewScarpino
MatthewScarpino

Reputation: 5936

There were two problems. First, I was importing Promise from es6-promise, which is different than the already-available Promise class. Thanks to Eric Martinez for figuring this out.

The second problem is this line of code:

this.promise.then(function(msg: string) { this.result = msg; });

The problem here is that, inside function(...) {...}, this doesn't refer to the enclosing Test object. To fix this, the function needs to be declared using fat-arrow notation:

this.promise.then((msg: string) => { this.result = msg; });

Just another fascinating piece of JavaScript trivia.

Upvotes: 7

Related Questions