Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 673
WasiF Avatar asked Feb 26 '18 12:02

WasiF


1 Answers

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() {
    }
}
like image 80
WasiF Avatar answered Sep 19 '22 13:09

WasiF