Creating services in Angular is a continuous process

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 {
}

Answer №1

There are multiple ways to implement a singleton service in Angular:

  1. Specify that the service should be available at the application root level.
  2. Add the service to the AppModule or a module exclusively imported by the AppModule.

According to the official documentation, you must declare in the @Injectable decorator of the service that it should be provided at the 'root'.

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

@Injectable({
  providedIn: 'root',
})
export class GlobalStateService {
}

Although it may seem correct based on the code, IMPORTANT : Remember to annotate it with

@Injectable({providedIn: 'root'})
and
avoid providing it in any providers array.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having some vertical alignment problems in Bootstrap 4 with float-right

My template includes a comments section where I have used the w-75 float-right class, but this causes the other column to be pulled to the side where the comments are displayed. https://i.sstatic.net/HSnGT.png Below is the code snippet from my template: ...

Unable to save data to file: ENOENT error - file not found

I'm currently working on creating a folder named "build" that will house numerous map files and JavaScript files. However, I've encountered the following issue. Snippet of the code: "scripts": { "prestart": "d2-manifest package.json manifes ...

Is the term 'Literal' in Javascript Arrays simply referring to its dynamic nature, allowing it to be modified at any time?

I'm confused why Mozilla refers to this as an Array 'Literal' when it's declared using the VARIABLE keyword and its content can be modified... var drinks = ["Espresso", "Latte", "Cappuccino"]; Could someone shed some light on this for ...

Module augmentations do not allow for exports or export assignments

import { Request as ExpressRequest, Response as ExpressResponse } from 'express'; declare module 'kvl' { export = kvl; } declare const kvl: { ValidationDone:(param:(error: any, response: ExpressResponse) => void) => void; ...

Is it possible to use a jquery selector to access dropdown options?

Having an issue with accessing a dropdown on my ASPX webpage using JavaScript. Here is the code I have tried: var dropDown = document.getElementById('myDropdown'); alert(dropDown.options.length); Unfortunately, this code is not working as inten ...

Exploring the application of javascript method within a Vue template

Currently, I am attempting to extract a numeric value from the end of a URL. However, I am encountering an error in doing so. It has been a while since I last worked with Vue, but I know that we can use methods/functions to achieve the desired outcome. Cou ...

How can you change the name of a component in Angular2 CLI?

If I were to create a component called 'Car', but later decided to change its name to 'Bicycle', is there a convenient way to do this quickly through the command line interface (CLI)? This includes changing the file names, class names, ...

Switch up a button counter

Is there a way to make the like count increment and decrement with the same button click? Currently, the code I have only increments the like count. How can I modify it to also allow for decrements after increments? <button (click)="toggleLike()"> ...

Using jQuery to serialize parameters for AJAX requests

I could use some help figuring out how to set up parameters for a $.ajax submission. Currently, I have multiple pairs of HTML inputs (i pairs): > <input type="hidden" value="31" name="product_id"> <input > type="hidden" value="3" name="qua ...

Notification on upcoming event date in FullCalendar

I've been thinking about the possibility of setting up a trigger to display something (like an alert, Qtip message, or any other notification) when today's date coincides with an event on my FullCalendar. Currently, I'm using XML from my Goo ...

Exploring how to read class decorator files in a Node.js environment

I've developed a custom class decorator that extracts permissions for an Angular component. decorator.ts function extractPermissions(obj: { [key: 'read' | 'write' | 'update' | 'delete']: string }[]) { re ...

Encountering a JS error while attempting to execute a basic HTTP request

I'm currently attempting to interact with a Gateway and decided to test out the https://www.npmjs.com/package/@types/request module. Below is the snippet of code I am trying to execute: export class OAuthAccessor { //some stuff public stat ...

"Styling a form input with YAML and implementing a jQuery date picker field

Seeking help with a CSS question related to YAML. I've been struggling all day trying to position a jQuery date field next to a YAML CSS field, but so far I can only manage to have it display underneath the input field... Is there a way for the date ...

Converting Typescript library into a standalone global JavaScript file

Currently working on developing a Typescript library that follows this structure: https://i.stack.imgur.com/YyCHk.jpg This includes the following files: restApi.class.ts import { restApiOptions } from '../models/rest.options.model'; import { ...

What steps are needed to design a search bar similar to Zomato's?

I am looking to create a search bar that resembles the one on . I have managed to make a floating search box on top of my background image. However, I am unsure how to align various input fields and buttons side by side. Below is the current CSS code I am ...

Delaying the loading time of certain ASP.NET components

I've been encountering an issue where the drop-down navigation bar is appearing flat and fully visible for a few seconds while a page is loading. This seems to occur specifically on pages with more content, leading me to believe that the navigation is ...

Retrieving the Textfield value upon clicking the InputAdornment in Material UI

I need help figuring out how to access the value of a Textfield after clicking on the icon within the InputAdornment. Initially, everything seemed to be working using OnChange, but now I'm receiving an output of undefined <Textfield id="se ...

What is the best way to extract plain text with JQuery?

I found this Html code snippet: <div class="form-group row"> <label id="lb_size" class="col-lg-3 col-form-label"> <span class="must-have">****</span> Size </label> </div> My goal is to ext ...

When utilizing useEffect in Next.js, an error may occur stating that the window is

It seems like there is a challenge with executing script code server side in next.js 13 when it needs to be executed client side. Currently, I am trying to implement the bulma calendar found at When importing the required library: import PasswordStrengthB ...

Learn how to create text animations using CSS triggered by a scroll event listener

I'm looking to create a text animation similar to the one on this website: They have 3 keyframes for two types of animations: Left to Right and Right to Left. The RTL animation starts at 164vh, while LTR starts at -200vh. These text animations only ...