然后Angular 2承诺

时间:2016-07-14 19:02:19

标签: angular promise

我正在使用Hero App进行Angular 2教程。我是本教程的Http部分。 (link

在hero.service.ts

中使用以下方法调用服务器
  getHeroes(): Promise<Hero[]> {
    return this.http.get(this.heroesUrl)
               .toPromise()
               .then(response => response.json().data)
               .catch(this.handleError);
  }

然后我尝试在下面的heroes.components.ts中使用返回的数据,但我无法正确实现then函数。我收到此控制台错误

  

EXCEPTION:错误:未捕获(在保证中):TypeError:this为null

export class HeroesComponent implements OnInit {

title = 'Tour of Heroes';
heroes: Hero[];
selectedHero: Hero;

constructor(
    private router: Router,
    private heroService: HeroService) { }

getHeroes() {
    this.heroService.getHeroes().then(function(value) {
        //SUCCESS
        console.log(value);  //this is working
        this.heroes = value; //this is not working
        console.log("I am inside then SUCCESS")
        console.log(title);
        console.log(this.heroes);

    }, function(error) {
        //FAILURE
        console.log(error);
    })

}

ngOnInit() {
    this.getHeroes();
}

你知道为什么我可以调试.log this.heroes title

4 个答案:

答案 0 :(得分:5)

您可能需要考虑使用胖箭头表示法来避免范围冲突。在您的情况下, this 不会指向类实例,而是指向您的承诺的sucesscallback。

getHeroes() {
    let instance : HeroesComponent = this;
    this.heroService.getHeroes().then((value) => {
        //SUCCESS
        console.log(value); 
        this.heroes = value; 
        console.log("I am inside then SUCCESS")
        console.log(this.title);
        console.log(this.heroes);

    }, (error) => {
        //FAILURE
        console.log(error);
    })
}

答案 1 :(得分:1)

范围问题,在 Typescript 中,在将代码传递给jquery或其他javascript API时会出现很多范围问题case,具有lambda函数。 要解决该问题,您需要将范围保存在变量中

getHeroes() {
    let instance : HeroesComponent = this;
    this.heroService.getHeroes().then(function(value) {
        //SUCCESS
        console.log(value);  //this is working
        instance.heroes = value; //this now works
        console.log("I am inside then SUCCESS")
        console.log(title);
        console.log(instance.heroes);

    }, function(error) {
        //FAILURE
        console.log(error);
    })

}

非常重要的注意事项: 不要使用 _this 来保存您的范围,因为它使用的是保留关键字来自动执行相同的操作,但不幸的是,它不能用于评论的案例。

答案 2 :(得分:1)

感谢您的所有答案。这是一个范围问题。

  

您可能需要考虑使用胖箭头符号来避免范围   冲突。在您的情况下,这不指向类实例,但   转而承诺你的承诺。

我使用了胖箭符号并解决了问题。

答案 3 :(得分:0)

你可能正在遇到一些范围问题...它正在查找它并不是你认为的那个。尝试这样的事情:

getHeroes() {
    let that = this; // use that now in all sub functions
    this.heroService.getHeroes().then(function(value) {
        //SUCCESS
        console.log(value);  //this is working
        this.heroes = value; //this is not working
        console.log("I am inside then SUCCESS")
        console.log(that.title);
        console.log(that.heroes);

    }, function(error) {
        //FAILURE
        console.log(error);
    })

}
相关问题