2017-10-10 56 views
0

In my Plunker here(改性Tour of Heroes从官方文档的应用程序),我创造了hero.service角:给一个组件领域的服务功能的参考和模板调用它无法正常运行

doHeroesExist(): boolean { 
    console.log("doHeroesExist called..", this.heroesExist); 
    alert("doHeroesExist called.." + JSON.stringify(this.heroesExist)); 
    return this.heroesExist; 
    } 

这种方法,并用它在app.component

ngOnInit(): void { 
    //this.getHeroes(); 
    this.heroesExist = this.heroService.doHeroesExist; 
    console.log("app ngOnInit called...", this.heroesExist); 

}

作为调用heroesExist()米模板中的方法

<button (click)="heroesExist()">Do Heroes Exist?</button> 

我对它的行为感到困惑。

当我点击做英雄存在吗?按钮,我希望控制台(和警报弹出)登录“doHeroesExist叫..真正的”,而是它记录了服务功能的整个身体:)

doHeroesExist叫..ƒ({ console.log(“doHeroesExist called ..”,this.heroesExist); (“doHeroesExist called ..”+ JSON.stringify(this.heroesExist)); return this.heroesExist; }

这是怎么发生的?

为什么服务不正确评估heroesExist = true;,因为它在服务的构造函数中定义?

PLUNKER LINK:https://plnkr.co/edit/MBEGkqnV5kie9PB3az9K?p=preview

+0

你正在对待'this.heroService.doHeroesExist'就像一个属性,rath呃比调用它像一个函数'this.heroService.doHeroesExist()'。最后遗漏了一些人。这是你真正需要的吗? –

回答

1

当你身边经过的功能,后来在另一种情况下调用它的this在功能的内容不会丢失。这就是为什么你看到显示“doHeroesExist called .. undefined”的警报,因为你服务方法中的this没有引用服务本身。

为了解决它,并且将功能作为一个变量之前,结合上下文它:

this.heroesExist = this.heroService.doHeroesExist.bind(this.heroService); 
+0

哦,我认为Typescript照顾这些问题。感谢您的解释! – CodyBugstein

+0

海洋组织这不是一个问题需要解决。 Typescript介绍了解决这个问题的另一种方法,即胖箭头功能。如果你使用这个'this.heroesExist =()=> this.heroService.doHeroesExist();' –

1

在乌尔plunker只需更换<button (click)="heroesExist()">Do Heroes Exist?</button>

<button (click)="heroService.doHeroesExist()">Do Heroes Exist?</button> 

,对于工作我

+0

这很酷。我没有想到它。我一直在组件中创建传递函数 – CodyBugstein

+0

看来,虽然我不得不将'heroService'作为'app.component'的公共字段, – CodyBugstein