Angular 2.0演示教程 - 解释

时间:2016-07-13 17:28:58

标签: service angular

我正在跟踪角度2.0第5节服务中的Heros教程。

文档说没有必要将this.heroes包装在函数

constructor(private heroService: HeroService) { }

this.heroService.getHeroes().then(heroes => this.heroes = heroes);

哪个不起作用。并收到错误

 Error: TypeError: Cannot read property 'getHeroes' of undefined(…)

然而,如果我使用onInit然后它可以工作(完成该部分)。

constructor(private heroService: HeroService) { 

    }
     ngOnInit() {
        this.getHeroes();
    }
    getHeroes() {
        this.heroService.getHeroes().then(heroes => this.heroes = heroes);
    }

为什么我只能在ngOnInit下运行时获得结果?

1 个答案:

答案 0 :(得分:0)

我的理解是组件类是一种工具箱,您可以在其中定义属性和方法。

然后,方法将响应Angular钩子(如ngAfterViewInitngOnInit)或事件,例如click()

有时组件需要在实例化时加载数据,在这种情况下,您可以使用ngOnInitconstructor来调用加载方法。

您不直接调用类定义中的方法。我认为,如果你这样做,那么在导入类或扩展类时可能会出现问题。

每次导入课程时,您都不希望课程获取您的数据;相反,您希望完全控制何时导入数据。

以下是best practices for Angular 2

相关问题