2017-10-09 48 views
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從不打印 - 進一步證明它不被稱爲!

回答

1

編輯:

你忘了提,你不得不在你的服務定義:

doHeroesExist: boolean; 

    constructor() { 
    this.doHeroesExist = true; 
    } 

不是一個好主意,有一個成員方法和成員字段使用相同的名稱...

無論doHeroesExist的定義是(function,other variable ...),在您的構造函數中,您只需將其賦值爲true。因此它變成boolean,其值爲true

就是這樣。由於名稱衝突,我感到驚訝,但無論如何,行爲顯然是由您的構造函數引起的。

+0

感謝您的有益答案並指出了這些問題。我現在意識到,我實際上已經磨礪了我的問題。我做了一些更改,並重新問它在這裏:https://stackoverflow.com/questions/46657227/angular-giving-a-component-field-a-reference-to-a-service-function-and-calling – CodyBugstein

相關問題