Shawn Shawn - 2 months ago 7x
TypeScript Question

Angular2 application scope variables

Is there a way to set certain application scope variable/constant that can be used by all components? If yes, where to declare it and how to reference it in components?

What I can think of is to

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

then import it in components and use it.

Can I declare something in main.ts and then directly reference it or something similar?


You could package that into a class and use it as a service. For example,

export class SharedValues {
    public Title = 'aaaaa';
    public Something = 'bbbbb';

Then, if you are using RC5 include in your module...

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

    // declarations, imports, bootstrap...

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

If you are using RC4 or previous add to your bootstrap...

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

bootstrap(AppComponent, [
    // ...

And wherever you want to use it...

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

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