Injecting Services Error in Angular

I'm in the process of developing a web App and recently put together a new service:

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

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

  constructor(private startTime: number = 8, private endTime: number = 12) { }

  get start() {
    return this.startTime;
  }

  get end() {
    return this.endTime;
  }

  set start(startTime) {
    this.startTime = startTime;
  }

  set end(endTime) {
    this.endTime = endTime;
  }
}

However, when I try to inject this service into a component, an error surfaces:

ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[Number]: 
  StaticInjectorError(Platform: core)[Number]: 
    NullInjectorError: No provider for Number!
Error: StaticInjectorError(AppModule)[Number]: 
  StaticInjectorError(Platform: core)[Number]: 
    NullInjectorError: No provider for Number!

Strangely enough, if I eliminate the attributes from the constructor, everything seems to work fine:

export class ModuleService {
  startTime = 8;
  endTime = 12;

  constructor() { }

After doing some research on https://angular.io/guide/dependency-injection#non-class-dependencies, it appears that when dealing with non-class dependencies (like numbers in my case), injecting an InjectionToken is recommended. So, now I am pondering between creating an injectionToken or simply declaring the attribute as shown above. Any thoughts on the best approach?

Answer №1

To have Angular automatically inject services for you, it needs to be aware of all the parameters in the constructor that will be passed into it during injection. In this case, there are 2 parameters with type number, which Angular does not recognize. This results in an error when trying to inject them. However, since these parameters have set/get functions and are primitive types, they can simply be declared as properties instead.

Creating InjectionToken's for the parameters is not an ideal solution, as it won't enhance your code - you would still need to declare and pass them into the constructor without actually calling it, as Angular handles that part. Therefore, it's better to just define them as properties directly.

Answer №2

To integrate this functionality into your module (within the component where you wish to utilize it), follow these steps:

import { CustomService } from '../../providers/customservice/customservice.service';

providers: [
    CustomService,
]

export class YourModule {}

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

When a class decorator is returned as a higher-order function, it is unable to access static values

Check out this showcase: function Decorator(SampleClass: Sample) { console.log('Inside the decorator function'); return function (args) { console.log('Inside the high order function of the decorator: ', args); let sample = ...

Error in Angular Material Snackbar issue

Within my Angular 4 project, I have successfully implemented MatSnackbar to display useful messages to the user. However, there is one instance where a particular snackbar displays an error. The issue arises when a user attempts to access the application ...

The error of 'illegal invocation' occurs when attempting to use input setCustomValidity with TypeScript

I am new to the Typescript world and currently converting one of my first React applications. I am facing an issue while trying to set custom messages on input validation using event.target.setCustomValidity. I keep getting an 'Illegal invocation&apo ...

Guide for setting up various validations for formGroup in an Angular 5 project

I am currently working on implementing Angular reactive form validation. My existing structure only includes validation for required fields, but I am looking to add additional validations such as minLength, email, and postcode. One challenge I face is cre ...

Tips for creating a breadcrumb navigation component in Angular inspired by the design of Windows File Explorer

When there are too many items in the breadcrumbs, I want to hide the older ones and only display the most recent ones. Here's a visual example of how it's done on Windows: view here ...

Using TypeScript or JavaScript, set object keys as fields of a class

I am looking for a way to update the properties of this class dynamically using an object export default class Foo { private accessKey: string; private workspaceId: string; private api: AxiosInstance; public bar: string; public name: s ...

TypeScript error TS6053: Unable to locate file '.ts'

I encountered the following issue: Error TS6053: Could not find file 'xxx.ts'. Oddly enough, the file compiled without any issues yesterday. However, today it seems to be causing trouble. To troubleshoot, I ran a simple test: class HelloWorl ...

Exporting data to CSV using PrimeNG

Utilizing a PrimeNG grid, the data being retrieved from a service is paginated on the server side. This means that only the current page's data is received at a time. The relevant HTML code is displayed below: <p-dataTable *ngIf="displayTable" # ...

Is it possible to utilize pinia getter as the initial parameter in Vue3's watch function?

Issue Recap In Vue3, can Pinia getters be utilized as a watch target's first argument? System Details Vue version: 3.2.13 Pinia version: 2.1.4 TypeScript version: 4.5.5 Problem Description An error was encountered when attempting to reference the ...

Tips for including and excluding personalized Chips from input

Just started learning React/typescript, any assistance would be greatly appreciated Custom Chip (CC.chip) is a specialized Chip UI component that can be utilized as demonstrated below. const [isOpen, setIsOpen] = useState(true); const onClose = Re ...

How can I store the status of checked and unchecked checkboxes in an array of objects using Angular 7?

I have a set of checkboxes with a parent-child structure, and their values are generated dynamically in a loop. When I click the submit button, I want to capture the selected or unselected values in the specified format (as shown in the commented output) ...

Creating a custom theme in MUI v5 by modifying ColorPartial members

I am seeking a solution to override certain members within PaletteOptions. My goal is to switch the type of grey from ColorPartial to PaletteColorOptions in order to include additional members. This was my attempt at implementing the necessary code: decl ...

Displaying svg files conditionally in a react native application

I have developed an app specifically for trading dogs. Each dog breed in my app is associated with its own unique svg file, which are all stored in the assets folder (approximately 150 svg files in total). When retrieving post data from the backend, I re ...

Is it secure to utilize Http.Get (with parameters) for accessing WebApis in Angular 2/4?

When calling a Web API in Angular, is it safe to use Http Get with passwords included in the fields? Or would it be more secure to utilize Http Post instead? Check out this example on how to execute an Http.get request in Angular: http.get(baseUrl + &apo ...

Issues with path in ngx-cookie-service while using Angular 9

I'm currently utilizing the ngx-cookie-service package to store important data for my application. It is crucial for me to save this cookie on the base path '/' so that I can easily retrieve it when needed. The cookie requires periodic updat ...

Merge a pair of observables to create a single combined output

Hey there, I'm currently diving into the world of RxJS and reactive programming. One challenge I'm facing is merging two observables. The first observable contains an array of objects called DefectImages[], while the second observable holds an ar ...

When utilizing a generic type with a class, type T fails to meet the specified constraint

export type ExtractType<T extends Array<{ name: Array<string>, type: keyof TypeMapping }>> = { [K in T[number]['name'][0]]: TypeMapping[Extract<T[number], { name: K }>['type']] } export class CommandLineParse ...

Error: Http post not found in Ionic framework version 3 and Angular versions 4 and 5

When using Postman, I successfully made a POST request to the following URL: https://myapp.herokuapp.com/login with the body containing email and password credentials. However, when attempting the same action in my provider, by sending a similar POST requ ...

By pairing delay(0) with refCount(), we can achieve optimal efficiency

The refCount operator is discussed in this article. It explains the necessity of adding delay(0) to prevent unsubscription of observable A: import { Observable } from "rxjs/Observable"; const source = Observable.defer(() => Observable. ...

Typegoose and NestJS: The 'save' property is not found on this type

I recently started using typegoose and nestjs for my backend-server. In my pages.service.ts file, I already have a function called getPageById() to retrieve a single page by its ID. However, when trying to call this function from another function within th ...