Error: Uncaught (in promise): NullInjectorError- Angular not able to find custom service

Once Again, I missed a small detail and got an error. Let me introduced you to the Error, detail, and Fix.

ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(HomePageModule)[RandomDateGenerateService -> RandomDateGenerateService -> RandomDateGenerateService -> RandomDateGenerateService]: 
NullInjectorError: No provider for RandomDateGenerateService!


I have created a service manually in the project. I import the same service in another component, and there were no compile-time errors.

So I built it and executed it by command:

>ionic build

>ionic serve

No error is showed in the VS Code terminal. But The application page was a completely blank screen on the browser. I inspect the page in the browser.  There I was able to find the error in the console tab.

Below is the code with the error:

Note: Pay attention to the Injectable Decorator

import { Time } from "@angular/common";
import { Injectable } from "@angular/core";

Injectable({
  providedIn: 'root'
})
export class RandomDateGenerateService{
  timeToMinuteConvert(time: Time){
      let timetoStringArray: string[]=time.toString().split(":",2);
      let timeStringtoNumberArray: number[]= [];

      for(let item of timetoStringArray){
          timeStringtoNumberArray.push(Number(item));
      }
      var minuteFromTime= timeStringtoNumberArray[0]*60+timeStringtoNumberArray[1];
      return minuteFromTime;
  }
}

 

Below is the corrected code:

Note: Pay attention to the Injectable Decorator

import { Time } from "@angular/common";
import { Injectable } from "@angular/core";
@Injectable({ 
  providedIn: 'root' 
})
export class RandomDateGenerateService{
    timeToMinuteConvert(time: Time){
        let timetoStringArray: string[]=time.toString().split(":",2);
        let timeStringtoNumberArray: number[]= [];

        for(let item of timetoStringArray){
            timeStringtoNumberArray.push(Number(item));
        }
        var minuteFromTime= timeStringtoNumberArray[0]*60+timeStringtoNumberArray[1];
        return minuteFromTime;
    }
}

 

Output: It worked and solved the error.

Explanation: Actually we need to tell Angular about the dependency of the service and components. There are 3 ways to do that

1. By using @Injectable

2. Adding provider in module

3. Adding provider in component

[click here  to know about them in detail.]

Here I am using an Injectable decorator. So, It should not show this error, But If you pay attention to the code, there is one big detail missing -"@". In the previous code "@" is missing. Therefore I got this error. Because Angular is not able to recognize the decorator without "@". So never forget to use "@" while using the decorator in Angular.

Hope this is helpful. Thank you

Reference: https://angular.io/guide/architecture-services

 

Add comment