Comparing Angular global variables: when to use static readonly in service class versus const

Which method is the better choice?

@Injectable({
  providedIn: 'root'
})
export class MyService {
  static readonly VALIDITIES = new Map<number, string>([
     ...
  ]);

  ...
}

OR:

const Validities = new Map<number, string>([
   ...
]);


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

I have mostly used the first approach before, but encountered an error when trying to combine two Maps. Interestingly, the error only occurs in my jasmine unit tests!

@Injectable({
  providedIn: 'root'
})
export class MyService {
  static readonly VALIDITIES = new Map<number, string>([
    [1, 'A'],
    [2, 'B'],
    [3, 'C'],
    [4, 'D']
  ]);

  static readonly VALIDITY_FILTERS = new Map<number, string>([
    [0, 'invalid'],
    ...Array.from(MyService.VALIDITIES.entries()), // XXXX
    [99, 'all']
  ]);

  ...
}

Error message in line (XXXX):

An error was thrown in afterAll
Uncaught TypeError: Cannot read properties of undefined (reading 'VALIDITIES')
TypeError: Cannot read properties of undefined (reading 'VALIDITIES')

What could be causing this issue in the code? Is there an alternative solution available?

Answer №1

The error message you're seeing is a result of theVALIDITIES property not being defined when the code is executed. This issue arises because the code attempts to access the VALIDITIES property before it has actually been set.

In this scenario, both the VALIDITY_FILTERS and VALIDITIES properties are declared within the same class, suggesting that they share the same lexical scope. However, as VALIDITY_FILTERS is a static property, it gets defined prior to the instantiation of the class. Consequently, during the definition of VALIDITY_FILTERS, VALIDITIES has not yet been defined, leading to an error if accessed.

A potential solution for this problem could look like:

@Injectable()
export class MyService {
  static readonly VALIDITIES = new Map<number, string>([
    [1, 'A'],
    [2, 'B'],
    [3, 'C'],
    [4, 'D']
  ]);

  static validityFilters(): Map<number, string> {
    return new Map<number, string>([
      [0, 'invalid'],
      ...Array.from(MyService.VALIDITIES.entries()),
      [99, 'all']
    ]);
  }
}

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

Navigating user profile routes effectively involves understanding the structure of the application

I'm currently working on developing a user-list feature that will display all users, along with user-detail components for each individual user. My main goal is to restrict access so that only administrators can see the complete list of users, while ...

Class for Eliminating the Background Image Using Bootstrap

Is there a Bootstrap class that can be used to remove a background image from a div? Currently, I have this style defined in my CSS: background-image: linear-gradient(to bottom, rgba(0,0,0,0.1), rgba(0,0,0,0)); I would like to remove it using: bg-img-non ...

Is there a way to configure routerLinkActive specifically for these routes?

My website has a navigation bar with the following items: Users, Categories, Products, etc. The routes are set as Main/Users, Main/Categories. I have successfully highlighted the items using routerLinkActive, however I also want to highlight the Users item ...

"Exploring the world of mocking module functions in Jest

I have been working on making assertions with jest mocked functions, and here is the code I am using: const mockSaveProduct = jest.fn((product) => { //some logic return }); jest.mock('./db', () => ({ saveProduct: mockSaveProduct })); ...

Filter the output from a function that has the ability to produce a Promise returning a boolean value or a

I can't help but wonder if anyone has encountered this issue before. Prior to this, my EventHandler structure looked like: export interface EventHandler { name: string; canHandleEvent(event: EventEntity): boolean; handleEvent(event: EventEntity ...

Execute Angular within a designated directory

Can Angular be launched in a custom URL path like http://localhost:4200/abcde instead of just http://localhost:4200/? I have been unable to find any settings for changing the pathname. ...

Transmitting MQTT information through an application programming interface

In my project using Ionic React, I am developing an application to showcase temperature data. To achieve this, I have established an API that transmits MQTT temperature information and utilize Axios for data retrieval. Despite my efforts, I am encountering ...

Encountered 'DatePickerProps<unknown>' error while attempting to develop a custom component using Material-UI and react-hook-form

Currently, I'm attempting to create a reusable component using MUI Datepicker and React Hook Form However, the parent component is throwing an error Type '{ control: Control<FieldValues, object>; name: string; }' is missing the follow ...

Using an array of strings as a key in React with TypeScript to access values from state

import React, { useState } from 'react'; interface PropsInterface { keys: string; // name,email,password } const Poster: React.FC<PropsInterface> = (props: PropsInterface) => { const [state, setState] = useState({ name: ' ...

Leveraging a service/provider in an Angular 2 ES6 component

I've been struggling to get a service to work properly in my component despite trying multiple iterations and exhausting all resources on Google. I've followed examples closely, and even tried using Ionic's generator to create the provider, ...

Retrieving source in Angular from an async function output within a specified time limit

I have a quick query :). I'm attempting to retrieve the image src from an async function, but so far, I haven't had much success. This is what I have: <img [src]="getProductImage(articleNumber)"/> and in my TypeScript file: publi ...

Encountering issues with `npm run build:prod` on Ubuntu 16.04, whereas it runs smoothly on

I've encountered errors when attempting to run "npm run build:prod" on Ubuntu 16.04, even though I don't face the same issues on Windows 10. Both npm and node are up-to-date. It's unclear whether the problem lies with npm or angular. After ...

What is the best way to implement automatic generation of varying numbers of tabs?

I'm facing an issue where the number of array items determines how many tabs are required. For example, if my array includes 'dog', 'cat', and 'mouse', I need 3 tabs named 'dog', 'cat', and 'mouse ...

Error Encountered During Angular 2 Protractor End-to-End Testing Runtime

Whenever I try to run protractor, I encounter this error message: [15:47:46] E/launcher - Error: TSError: ? Unable to compile TypeScript Conflicting library definitions for 'selenium-webdriver' found at 'G:/WebServers/home/smsc/SMSC2/module ...

Utilize Property Binding to Access the Map

I am struggling to extract a value from a Map and use it as the background color of a div element, but I can't seem to get it right. My syntax seems off. What mistake am I making? <div [style.background-color]="bgcolor" width="50px" height="50px"& ...

Angular Material SlideToggle Fails to Toggle

I am having issues with a specific Angular component called "new-form" that incorporates a slide toggle feature from the Angular Material library. Despite rendering on the client side, the slide toggle does not respond to clicks when interacted with. Even ...

What is the best way to locate this particular element on the webpage?

After using the right-click and selecting inspect element, I located the code of the desired element on the webpage: <input type="text" ng-if="!editing" ng-model="item.Price" ng-click="inputFocus()" ts="" required="" placeholder="قیمت :" class="ng- ...

Guide to setting the order of rendering in React applications

I am currently working with a .tsx file that renders two components: export default observer(function MyModule(props: MyModuleProps) { .... return ( <div> <TopPart></TopPart> <LowerPart>< ...

Typescript encounters issues when assigning declaration as TRUE

Currently, I'm working on a project in Angular 2 and attempting to create TypeScript definitions for it so that it can be exported as a library. I have various services set up that make HTTP requests to components, all structured similarly to the cod ...

Optimizing my AngularJS bundle is pushing me towards upgrading to Angular 5

Regarding my AngularJS application, it was initially created using 'yo angular-fullstack' with JS scripting instead of TS. It is functional but experiencing performance and user experience issues. The deployment is on AWS ElasticBeanstalk nano i ...