2016-07-28 129 views
4

有没有办法设置某个应用程序范围变量/常量可供所有组件使用?如果是,在哪里声明它以及如何在组件中引用它?Angular2应用程序范围变量

我能想到的是

export var SharedValues = { 
    Title: "aaaaa", 
    Something: "bbbbb" 
} 

然后将它导入组件和使用它。

我可以在main.ts中声明一些东西,然后直接引用它或类似的东西吗?

回答

3

您可以将其打包到一个类中,并将其用作服务。例如,

@Injectable() 
export class SharedValues { 
    public Title = 'aaaaa'; 
    public Something = 'bbbbb'; 
} 

然后,如果你正在使用RC5包括你的模块中...

import { SharedValues } from 'some/path/shared-values.service'; 

@NgModule({ 
    // declarations, imports, bootstrap... 

    providers: [ 
     // your other providers 
     SharedValues, 
    ] 
}) export class AppModule {} 

如果您正在使用RC4或以前添加到您的引导......

import { SharedValues } from 'some/path/shared-values.service'; 

bootstrap(AppComponent, [ 
    // ... 
    SharedValues, 
]); 

无论你想使用它...

import { SharedValues } from 'some/path/shared-values.service'; 

// or wherever you want to use the variables 
@Component({ 
    // ... 
}) export class SomeComponent { 
    constructor(private shared: SharedValues) { 
     console.log(this.shared.Title, this.shared.Something); 
    } 
} 
+0

谢谢,这是@NgModule语法只适用于RC5? – Shawn

+0

是的,我会编辑包含RC4的答案 – jcolemang