Angular Singleton Service creates multiple new instances despite root injection & single providers declaration

Viewed 699

I'm trying to create a service that holds variables that my Angular web app shares across components (components that can read and write to those variables). Because of this, I need it to be a singleton service, but I'm having no luck, as a new instance is created with each new component.

The Service (GlobalService) is declared as follows:

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

@Injectable({
  providedIn: 'root',
})

export class GlobalService {

  currentUser: string = null;
  currentProject: string = null;
  currentProjectName: string = null;
  canEditInProject: boolean = null;

  constructor() {
    console.log('in global service constructor');
  }

with getter and setter methods defined after.

In app.module.ts I have the following:

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    FontAwesomeModule,
    FlexLayoutModule,
    RouterModule.forRoot([]),
    LayoutModule,
    MDBBootstrapModule.forRoot(),
    BrowserAnimationsModule,
    HttpClientModule,
  ],
  providers: [GlobalService],
  bootstrap: [AppComponent]
})

where it is declared in providers. I've searched my project and there are no other provider statements with the service.

Each component that uses it (1) has an import statement up top and then (2) declares a private variable in it's constructor, ex:

constructor(private globalService: GlobalService)

and uses the this.globalService variable to get or set the service variables.

Nonetheless, with each new page load, I see from my print statement in global.service.ts that the constructor is called, and a new instance is created. Then of course, all my variables are null and nothing persists.

Any idea what's going wrong? Or any other solution ideas? I tried using localStorage and sessionStorage before, but had some instability there as well.... I'm stumped

0 Answers
Related