2017-06-30 67 views
-1

我正在構建一個基於Angular 2的應用程序。我想要一個全局變量,可以被所有組件訪問和修改。 我能找到的所有當前答案都是常量。任何人都可以建議我怎麼能這樣做? 謝謝!Angular 2中的全局變量

+1

我相信一個共享服務將是要走的路:https://angular.io/guide/component-interaction – Alex

+0

[這個問題](https://stackoverflow.com/questions/11938380/glo bal-variables-in-angularjs)回答你的問題? – JiFus

+0

首先,你確定擁有全局變量是一個好主意嗎? – helcim

回答

0

當我必須處理全局變量時,我通常通過共享服務來完成。我在根組件的服務中聲明瞭一個變量,通常是app.service.ts,並通過setter和getter函數使其可用於其他組件。

爲了演示,我使用了一個有三個組件的英雄教程plunker。在app.service.ts我宣佈變量myGlobalVar

我在所有其他組件中添加了按鈕來更改myGlobalVar的值,並隨時查找它的值。

你可以找到這個example

app.service.ts交互細節:

@Injectable() 
export class AppService{ 
    myGlobalVar; 

    constructor(){ 
     this.myGlobalVar = true; 
     console.log("My global variable value: " + this.myGlobalVar); 
     alert("My intial global variable value is: " + this.myGlobalVar); 
    } 

    setMyGV(val: boolean){ 
     console.log("Setting FV to: " + val); 
     this.myGlobalVar = val; 
    } 

    getMyGV(val: boolean){ 
     return this.myGlobalVar; 
    } 
} 

訪問和修改從組件變量:

export class exampleComponent{ 
    constructor(private appService: AppService) {} 

    changeGV(val){ 
     this.appService.setMyGV(val); 
    } 

    showGV(){ 
     alert("GV: " + this.appService.getMyGV()); 
    } 
}