NullInjectorError: No provider for class
Asked Answered
L

2

9

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?

Lucilius answered 26/2, 2018 at 12:26 Comment(2)
If formation is a service add it to providers in your app module. If it is not a service then it should be, use Injectable annotation.Compte
it's a simple class that represents the data model. How to annotate a class and why we can't define it like a simple class in C#. Can you show me pleaseLucilius
L
21

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() {
    }
}
Lucilius answered 27/2, 2018 at 7:9 Comment(1)
Working in Ang 7:: @Injectable({ providedIn: 'root' }) export class LoginComponent implements OnInit {Gena
I
0

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

Intake answered 18/12, 2019 at 16:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.