Search code examples
angularangular2-services

NullInjectorError: No provider for class


I have injected class as dependency injection in component class and get an error

NullInjectorError: No provider for class

Here is my code:

// Component
import { Formation } from './Models/Formation';

export class FormationComponent {
  constructor(private formation: Formation) { }
}

// Model Class
export class Formation {
}

What would be the problem?


Solution

  • Angular 6+

    import { Injectable } from '@angular/core';
    
    @Injectable({
      providedIn: 'root'
    })
    export class MyService {
        
        constructor() {
        }
    }
    

    Angular 5

    Method 1. add class in app.module.ts's providers

    @NgModule({
      // ----
      providers: [
        MyService // added class in the providers
      ]
      // ----
    })
    export class AppModule { }
    

    Method 2. add class in component's provider

    @Component({
      selector: 'app-my-component',
      templateUrl: './my-component.component.html',
      styleUrls: ['./my-component.component.scss'],
      providers: [
        MyService // added class in the providers
      ]
    })
    export class MyComponent {
    
      constructor(private service: MyService) {
      }
    
    }
    

    Important: Please don't forget to annotate the class as @Injectable so that you can inject it in the constructor i.e.

    import { Injectable } from "@angular/core";
    
    @Injectable() // class annotation as Injectable
    export class MyService {
    
        constructor() {
        }
    }