WasiF
WasiF

Reputation: 28859

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?

Upvotes: 9

Views: 45347

Answers (2)

WasiF
WasiF

Reputation: 28859

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() {
    }
}

Upvotes: 21

Gopi P
Gopi P

Reputation: 437

I faced the same issue and the solution is to add the service reference in the app module. once included then you can easily get rid out of it.

NOTE: Angular 4 are same solution. Checked

Upvotes: 0

Related Questions