0

I am building a web App and I created a 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;
  }
}

When I inject this in a component I have the following error:

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!

When I remove the attributes from the constructor it works

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

  constructor() { }

I read here https://angular.io/guide/dependency-injection#non-class-dependencies that I have to inject an InjectionToken when it's a non-class dependencie (a number in my case). So my question is which is the best way, is it by creating an injectionToken or by declaring the attribute as I did above?

2 Answers 2

1

If you want Angular to inject services automatically for you, it must know all parameters in the constructor, which will be passed into it during injection. Now you have 2 parameters with type number. Angular does not know anything about this parameters, so why it can't inject them and throws error. Because you have set/get functions for these parameters and they are primitive types, you can just make them as a properties which you have done.

Declaring InjectionToken's for the parameters is not a good solution, because in that case you will not have any improvement in your code - you will declare two of them, pass them again into the constructor, but you will not call that constructor, it will do Angular. So just declare them as properties.

Sign up to request clarification or add additional context in comments.

Comments

0

Add this to your module(in module of the component that you want to use):

import { YourService} from '../../providers/yourservice/yourservice.service';

providers: [
    YourService,
]

export class YourModule {}

1 Comment

No this does not work, as @SurenSrapyan said, 'Angular does not know anything about this parameters [number]' so adding the service to the module won't make any difference

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.