I'm following the quickstart tutorial for Angular 2 (https://angular.io/docs/ts/latest/tutorial/toh-pt4.html#!#review-the-app-structure) and I got stuck in the Services chapter. This is my 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 you can see it implements OnInit
, which executes the component's getHeroes
method, which in turns calls the injected HeroService
:
import { Injectable } from 'angular2/core';
import { HEROES } from '../hero/hero.mock';
@Injectable()
export class HeroService {
public getHeroes() {
return Promise.resolve(HEROES);
}
}
The promise resolves successfully and I get the array from hero.mock.ts
in the response variable:
getHeroes() {
this._heroService.getHeroes().then(heroes => // heroes = Array[10]
this.heroes = heroes
);
}
The problem I'm facing is the first this
(this._heroService
) is correctly set to MainComponent
, but the second one (this.heroes
) is referencing the Window
javascript object. I've checked several other answers, including this and done as they suggest, but the problem remains. Can anyone think of a reason why this is happening?
Edit: Generated javascript for 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 I change the method calling the service to this (note the curly brackets wrapping everything after the =>
) then this
is MainComponent
, but neither the changes in the title nor in the heroes
array are reflected in the view:
getHeroes() {
this._heroService.getHeroes().then(heroes => {
console.log(this);
this.title = 'modified string';
this.heroes = heroes;
});
}