2

我正在关注 Angular 2 的快速入门教程(https://angular.io/docs/ts/latest/tutorial/toh-pt4.html#!#review-the-app-structure),但我被困在了服务中章节。这是我的组件:

@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; }
}

如您所见,它 implements OnInit,它执行组件的getHeroes方法,然后调用注入的方法HeroService

import { Injectable } from 'angular2/core';
import { HEROES } from '../hero/hero.mock';

@Injectable()
export class HeroService {
  public getHeroes() {
    return Promise.resolve(HEROES);
  }

}

承诺成功解决,我从hero.mock.ts响应变量中获取数组:

getHeroes() {
  this._heroService.getHeroes().then(heroes =>  // heroes = Array[10]
    this.heroes = heroes
  );
}

我面临的问题是第一个this( this._heroService) 正确设置为MainComponent,但第二个 ( this.heroes) 正在引用Windowjavascript 对象。我已经检查了其他几个答案,包括这个并按照他们的建议完成了,但问题仍然存在。谁能想到发生这种情况的原因?

编辑:为 MainComponent#getHeroes 生成的 javascript

MainComponent.prototype.getHeroes = function () {
    var _this = this;
    this._heroService.getHeroes().then(function (heroes) {
        return _this.heroes = heroes;
     });
};
MainComponent.prototype.ngOnInit = function () {
    this.getHeroes();
};

另一个编辑: 如果我将调用服务的方法更改为此(注意在 之后包含所有内容的大括号=>),那么this is MainComponent,但标题和heroes数组中的更改都不会反映在视图中:

getHeroes() {
  this._heroService.getHeroes().then(heroes => {
    console.log(this);
    this.title = 'modified string';
    this.heroes = heroes;
  });
}
4

0 回答 0