How does one store constants in Angular 2+?

494 Views Asked by At

This is a follow-up question to an earlier question I posted.

My question there was about strange log output I was getting when calling a method on a service. The console.log output was not printing the data that the service clearly defined. The culprit as it turns out was that when calling the service method, the context that is used is the context of the component making the call.

So my question is: What is the proper way to store variables across multiple components in Angular 2+?

For example, say I wanted to keep a variable isLoggedIn. Where do I keep this variable? I cannot keep it in a service because when components call that service (i.e. authService.getLoggedInStatus()) they will not neceesarily get the isLoggedIn value of the service, but rather, potentially, of an identically named variable in the component.

So how do you keep track of shared variables in Angular?

2

There are 2 best solutions below

0
On

If you would like to keep a global variable isLoggedIn accessable anywhere in the application, placing it in a @Injectable service as a singleton service is completely valid. In order to make sure it is singleton service you should only declare it in app.modules e.g

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { SingletonService } from './Singleton.service';

@NgModule({
 declarations: [
    AppComponent,
 ],
 imports: [
    BrowserModule,
    FormsModule
 ],
 providers: [SingletonService],
 bootstrap: [AppComponent]
})
export class AppModule { }

If you also add it in the components via so:

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
  providers: [SingletonService]
})

You initialize a new Service instance, and your intended global isLoggedIn would have it's own instance in this component.

Hope this give you some sense of how to store global variables using @Injectable() in angular.

More information on Dependency Injection here.

0
On

@Injectable services are singleton. You provide this service on the relevant module that the components are declared upon. Via dependency injection of this service in subject components you can access its public properties. Thus, you can share these properties and their values