Angular2 application scope variables

Is there a way to set some variable / constant of the application area that can be used by all components? If so, where to declare it and how to refer to it in components?

I can think of

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

then import it into components and use it.

Is it possible to declare something in main.ts and then directly reference it or something like that?

+4
source share
1 answer

You can pack this into a class and use it as a service. For instance,

@Injectable()
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';

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

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

If you are using RC4 or a previous add-on to your boot block ...

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

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

And wherever you want to use it ...

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);
    }
}
+3
source

Source: https://habr.com/ru/post/1649440/


All Articles