angular 2: when resolving promise in component via service 'this' is 'window' -


i'm following quickstart tutorial angular 2 (https://angular.io/docs/ts/latest/tutorial/toh-pt4.html#!#review-the-app-structure) , got stuck in services chapter. component:

@component({   selector: 'main',   templateurl: 'main/main.template.html',   styleurls: ['main/main.component.css'],    providers: [heroservice],   directives: [herocomponent] })  export class maincomponent implements oninit {   title: string = 'tour of heroes';   heroes: hero[];   selectedhero: hero;    constructor(private _heroservice: heroservice) {    }    getheroes() {     this._heroservice.getheroes().then(heroes =>       this.heroes = heroes     );   }    ngoninit() {     this.getheroes();   }    onselect(hero: hero) { this.selectedhero = hero; } } 

as can see implements oninit, executes component's getheroes method, in turns calls injected heroservice:

import { injectable } 'angular2/core'; import { heroes } '../hero/hero.mock';  @injectable() export class heroservice {   public getheroes() {     return promise.resolve(heroes);   }  } 

the promise resolves , array hero.mock.ts in response variable:

getheroes() {   this._heroservice.getheroes().then(heroes =>  // heroes = array[10]     this.heroes = heroes   ); } 

the problem i'm facing first this (this._heroservice) correctly set maincomponent, second 1 (this.heroes) referencing window javascript object. i've checked several other answers, including this , done suggest, problem remains. can think of reason why happening?

edit: generated javascript maincomponent#getheroes

maincomponent.prototype.getheroes = function () {     var _this = this;     this._heroservice.getheroes().then(function (heroes) {         return _this.heroes = heroes;      }); }; maincomponent.prototype.ngoninit = function () {     this.getheroes(); }; 

another edit: if change method calling service (note curly brackets wrapping after =>) this is maincomponent, neither changes in title nor in heroes array reflected in view:

getheroes() {   this._heroservice.getheroes().then(heroes => {     console.log(this);     this.title = 'modified string';     this.heroes = heroes;   }); } 


Comments

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

reactjs - React router and this.props.children - how to pass state to this.props.children -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -