角度2:当通过服务解决组件中的承诺时“这个”是“窗口”

时间:2016-03-07 06:53:20

标签: angular this angular-promise angular2-services

我正在关注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; }
}

正如您所见,它实现了OnInit,它执行组件的getHeroes方法,该方法又调用注入的HeroService

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

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

}

promise成功解析,我在响应变量中从hero.mock.ts获取数组:

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

我遇到的问题是第一个thisthis._heroService)被正确设置为MainComponent,但第二个this.heroes)引用了{Window 1}} javascript对象。我已经检查了其他几个答案,包括this并按照他们的建议完成,但问题仍然存在。任何人都可以想到这种情况发生的原因吗?

编辑:为MainComponent生成javascript#getHeroes

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

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

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

0 个答案:

没有答案