typescript – Angular2应用程序范围变量

前端之家收集整理的这篇文章主要介绍了typescript – Angular2应用程序范围变量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有办法设置可供所有组件使用的某个应用程序范围变量/常量?如果是,在哪里声明它以及如何在组件中引用它?

我能想到的是

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

然后将其导入组件并使用它.

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

解决方法

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

@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或之前添加到您的bootstrap …

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);
    }
}

猜你在找的Angularjs相关文章