What is the reasoning behind the preference in Angular 2+ for storing shared variables in services instead of directly importing them from a constant object?

As I delve into creating a Single Page Application with Angular 7, I find myself questioning the prevalent recommendation of storing data in services as opposed to a file with constants that can be directly imported. The simplicity of directly importing a constant is appealing, so what am I missing here?

Here's a snippet of my current code:

userSession.ts

export const userSession = {
    loggedIn: null,
    userId: null
};

something.service.ts:

import { userSession } from '../appGlobals/user-session';
// decorators, etc .......
export class SomethingService {  
  constructor() { }
  doSomething() {
    if (userSession.loggedIn) {
      // carry out an action
    }
}

The conventional approach suggests the following setup:

user.service.ts

//imports and decorator ....
export class UserService {
  session = {
    loggedIn: boolean;
    userId: number;
  }
//...
}

some.service.ts

import { UserSession } from '../services/user.service.ts';
// decorators, etc .......
export class SomeService {
  constructor(private userService: UserService) { }
  doSomething() {
    if (this.userService.session.loggedIn) {
      // perform a task
    }
  }
}

When dealing with extensive classes utilizing user session fields, using the "userSession" object seems more streamlined than accessing "this.userService.session" by injecting the dependency into the constructor. So, what are the pros and cons of each approach?

Answer №1

While discussing the example you mentioned, I believe there is not much of a difference. However, it is worth noting that shared variables may not always be ready when a component that uses them is fully loaded. This means that the variable may be populated after an API call. This is why services are often favored as they can offer functionalities to manage these shared variables in a neat and efficient manner. Additionally, many of these shared variables are Observable objects that can notify components using them when the value is available (especially useful in cases where values are filled later on or are subject to change).

Answer №2

Testing is a major benefit.

By declaring userSession outside of the class in your code, it becomes challenging to write unit test code.

However, by injecting the service in the constructor as suggested, test code can easily be written using the service or a mock service.

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 difficulty interpreting the information from angular's httpclient json request

After creating an Angular function in typescript to make an http request for JSON data and save it to an object, I noticed that the function requires two clicks of the associated button to work properly. Although the connection and data parsing are success ...

Handling a callback after the completion of another action in Angular 2

I am facing an issue where I need to delete an item from a list and then update the page to reflect that change. The current code handles the deletion of the item using DELETE_APPLICATION and then fetches the updated list using GET_INSIGHT_APPLICATIONS. Ho ...

Problem arises when combining string manipulation and piping operations

I have an HTML code within an Angular 2.0 template that looks like this: <span> Total Employee {{employeeCount> 0 ? '(' + employeeCount+ ')' : ''}} ></span> My customFormatter function is able to take a val ...

Compilation of Angular 6 project is failing due to error TS1005: Expected ',' instead of the symbol used

I keep encountering an error message whenever I try to compile my code. ERROR in src/app/form/form.component.ts(22,39): error TS1005: ',' expected. Below is the snippet of code where the error is pointing: import { Component, OnInit } from &ap ...

I am on the lookout for an Angular 2 application that utilizes Gulp to generate a distribution folder with the newest @angular frameworks

I'm on the lookout for an Angular2 application that incorporates Gulp to generate a 'dist' folder using the most recent @angular libraries. Although I've come across some online examples, they do not utilize the latest @angular librari ...

Can all objects within an interface be iterated through in order to retrieve both the key and its corresponding value?

I have created an interface that is capable of accepting a variety of search criteria and then passing it to a service that will incorporate those values into the service URL. I am wondering if there is a way to iterate through all the objects in the inter ...

A guide to finding the mean in Angular by utilizing JSON information

import { Component, OnInit } from "@angular/core"; import { MarkService } from "../app/services/marks.service"; @Component({ selector: "app-root", templateUrl: "./app.component.html", styleUrls: ["./app.component.scss"] }) export class AppComp ...

Tips for deploying an Angular Universal 9 application on a live server

Our Angular 9 app functions perfectly when deployed on an IIS server. We also have a version of the app that has been integrated with Universal by another company. Now, we need to figure out how to deploy our app with server-side rendering into productio ...

Encountering memory leaks and displaying repetitive data due to having two distinct observables connected to the same Firestore

I am currently utilizing @angular/fire to retrieve data from firestore. I have two components - one serving as the parent and the other as the child. Both of these components are subscribing to different observables using async pipes, although they are bas ...

Filtering database results from an Angular component

I am currently working on an Angular component and I have a result variable in the .ts file that stores data retrieved from the database. My goal is to filter this result variable to display only 20 records and sort them by date either in ascending or de ...

Communicate between sibling components in Angular by passing the selector of one component to another

Within my project, I have two sibling components located in the SecondComponent folder. The SecondComponent consists of both the main component and its child component. Now, in the FirstComponent, I need to access the child component of the SecondComponent ...

Simulated FileList for Angular 5 App Unit Testing

Imitation FileList In my pursuit of writing a unit test (Angular5), I have encountered the need for a FileList. Despite researching extensively, I have been unable to uncover any clues or solutions. I am starting to question whether this is even feasible ...

When clicking on absolute URLs, Angular Router Navigation Events are not triggered

Hey there! I need to reset certain values when we navigate away from the current page by clicking on an anchor link with an absolute URL. I've tried using the router events code below, but it only works for relative URLs and not absolute URLs. Is the ...

Web-based API for authentication system using Ionic framework and token-based login

I am developing a photo-sharing app that requires a login system. However, when attempting to log in, an error occurs stating that the value is not found. I am able to retrieve the value in services but struggling to get the email and password in login.pag ...

What steps should I take to enable a route guard to authenticate a token once it has been stored in local storage?

I'm currently working on a basic login page with authentication using Angular and Express. Here's what I've got so far: a login component a service that handles http requests and stores the jwt token in local storage a route guard for the ...

Error message: "ExpressionChangedAfterItHasBeenCheckedError - encountered while using ngIf directive to hide/show a progress

My HTTP interceptor is set up to display a loading bar whenever an HTTP request is made: intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const dataStorageService = this.injector.get(DataStorageService); ...

Angular: encountering template parse errors with unknown <component> element

I'm struggling to import a component into another component, but the imported component cannot be found. Here is the error message: Uncaught Error: Template parse errors: 'aktenkorrespondenzenTemplate' is not a known element: 1. If 'ak ...

Guide to accessing contact list on Ionic framework

I'm new to using Ionic and I'm trying to access the contact list in my app to display contacts only. Can someone please guide me on how to achieve this? I watched a tutorial on YouTube but the code provided doesn't seem to work. I've ad ...

What causes BehaviorSubjects in Angular RXJS to emit multiple values?

click here to see the image descriptionUsing BehaviorSubject for sharing data between components in my app has led to a performance problem caused by multiple emissions of the same value. For example, when I make an HTTP call to fetch a team object from th ...

Modify the color of the designated Tab in the PRIMENG TabMenu - customize the style

Currently, I am utilizing the Primeng tab menu component and facing an issue. Unfortunately, I seem to be unable to identify a method to alter the color of the selected tab to a different shade. If anyone has any insights or suggestions on how to achieve ...