How can I create a service as singleton in Angular?
I have a service that is injected into 2 components and the value is set to true. However, every time I open the view, the service is created again and the value resets to false. How can I make sure the service is only created once?
import {Injectable} from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class GlobalStateService {
constructor() {
console.log('GlobalState created');
}
myValue = false;
}
This is how I use the service:
@Component({
selector: 'app-nav',
templateUrl: './nav.component.html',
styleUrls: ['./nav.component.css']
})
export class NavComponent implements OnInit {
model: any = {};
permission: any;
constructor(public authService: AuthService,
private alertifyService: AlertifyService,
private globalState: GlobalStateService) {
}
Here is the module setup:
import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {HttpClientModule} from '@angular/common/http';
import {FormsModule} from '@angular/forms';
import {AppComponent} from './app.component';
import {NavComponent} from './nav/nav.component';
import {AuthService} from './_services/auth.service';
import {HomeComponent} from './home/home.component';
import {RegisterComponent} from './register/register.component';
import {AlertifyService} from './_services/alertify.service';
import { SettingsComponent } from './settings/settings.component';
import { BooksComponent } from './books/books.component';
import { UsersComponent } from './users/users.component';
import { GlobalStateService } from './_services/global-state.service';
import { StoreModule } from '@ngrx/store';
import { changeTabReducer } from './reducers/tab.reducer';
@NgModule({
declarations: [
AppComponent,
NavComponent,
HomeComponent,
RegisterComponent,
SettingsComponent,
BooksComponent,
UsersComponent
],
imports: [
BrowserModule,
HttpClientModule,
FormsModule
],
providers: [
AuthService,
AlertifyService,
GlobalStateService
],
bootstrap: [AppComponent]
})
export class AppModule {
}