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?
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class MyService {
constructor() {
}
}
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() {
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With