What is the best way to declare a global variable in Angular

https://stackoverflow.com/questions/36158848/what-is-the-best-way-to-declare-a-global-variable-in-angular-2-typescript

A shared service is the best approach

export class SharedService {
  globalVar:string;
}

But you need to be very careful when registering it to be able to share a single instance for your whole application. You need to define it when registering your application:

bootstrap(AppComponent, [SharedService]);

but not to define it again within the providers attributes of your components:

@Component({
  (...)
  providers: [ SharedService ], // No
  (...)
})

Otherwise a new instance of your service will be created for the component and its sub components.

You can have a look at this question regarding how dependency injection and hierarchical injectors work in Angular2:

You can notice that you can also define Observable properties in the service to notify parts of your application when your global properties change:

export class SharedService {
  globalVar:string;
  globalVarUpdate:Observable<string>;
  globalVarObserver:Observer;

  constructor() {
    this.globalVarUpdate = Observable.create((observer:Observer) => {
      this.globalVarObserver = observer;
    });
  }

  updateGlobalVar(newValue:string) {
    this.globalVar = newValue;
    this.globalVarObserver.next(this.globalVar);
  }
}

See this question for more details:

About Nguyễn Viết Hiền

Passionate, Loyal
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s