1
In this Plunk,我對Angular.io教程做了一個小改動。角度服務被引用但未被調用,但仍然「返回」正確的值
我已經爲heroes.service添加了一個名爲doHeroesExist
的函數。 但是,我從來不稱它。我這樣做的唯一的事情把它分配給一個變量在app.component
ngOnInit(): void {
//this.getHeroes();
this.heroesExist = this.heroService.doHeroesExist;
console.log("app ngOnInit called...", this.heroesExist); // outputs: app ngOnInit called... true
}
這裏是hero.service.ts
文件中的doHeroesExist
功能。
doHeroesExist(): boolean {
console.log("doHeroesExist called..", this.doHeroesExist);
return this.doHeroesExist;
}
我很困惑。
爲什麼在控制檯日誌中說爲真?不應該以字符串形式輸出函數體嗎?此外,doHeroesExist
內的console.log從不打印 - 進一步證明它不被稱爲!
感謝您的有益答案並指出了這些問題。我現在意識到,我實際上已經磨礪了我的問題。我做了一些更改,並重新問它在這裏:https://stackoverflow.com/questions/46657227/angular-giving-a-component-field-a-reference-to-a-service-function-and-calling – CodyBugstein