George Edwards George Edwards - 1 year ago 67
TypeScript Question

App wide variables in Angular2 (RC5)

I want to create an application wide variable accessible between various angular2 components and imported modules.

I have looked at dependency injection in my

and thought maybe I could set a class with a property in that. However, with the new angular-RC5 release, this looks like an overcomplication for what I want to do.

Alternatively, I thought of using a @Inputs and @Outputs to cascade the data and subscribe to changes, however, that doesn't seem to be possible between modules.

I would be really grateful for a suggestion of the easiest way of doing this.

In terms of my particular application, I have a navbar component which I want to show on all routes except one. So I have that on my
template, with an *NgIf condition, which I then wanted to be able to change from various child components to display the navbar, without having to embed the navbar component in all of my child modules and components (which gets tricky with components being shared between modules. Some of my routes are imported in a module.

Answer Source

You can create a shared service.

something like that :

import { Injectable } from '@angular/core';

export class GenericService {
    data:any = {};

and then add it to your app.module.

after that you can inject it to your component and add datas on it who will be accessible from all your components.