abrahamlinkedin
abrahamlinkedin

Reputation: 467

Use Angular 2 Services to pass global variables?

In our NG starter boilerplate app.component.ts I have this code:

export class AppComponent {title = "Website Title"}

In the appropriate app.component.html, title will be included as follows:

<p>{{title}}</p>

But I would like to include this title variable globally. Let's say my structure was as follows:

app.component.html app.component.ts test.component.html test.component.ts

In test.component.html I would like to display the same information.

<p>The title of this website is {{title}}</p>

And the value of {{title}} would be derived from my app.component.ts. How would I use services to pass something like a string? Would it be worth passing in a directive instead? Something like:

<p>The title of this website is <app-test></app-test></p>

Upvotes: 0

Views: 840

Answers (1)

Kamil Myśliwiec
Kamil Myśliwiec

Reputation: 9178

If it is necessary to use global variables, which are available in entire application structure, you can use shared service, which you have to place in shared module.

You can read about shared module here:

https://angular.io/docs/ts/latest/guide/ngmodule.html#!#shared-module

This kind of service class could looks like this (public variable in this example):

@Injectable()
export class SharedService {
      globalVariable = "default";
}

In fact, I think it is not a good idea to have something like this in any app.

Upvotes: 1

Related Questions