我在组件类中将类作为依赖注入(inject)注入(inject)并出现错误
NullInjectorError: No provider for class
这是我的代码:
// Component
import { Formation } from './Models/Formation';
export class FormationComponent {
constructor(private formation: Formation) { }
}
// Model Class
export class Formation {
}
会有什么问题?
最佳答案
Angular 6+
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class MyService {
constructor() {
}
}
Angular 5方法一。在
app.module.ts
中添加类的提供者@NgModule({
// ----
providers: [
MyService // added class in the providers
]
// ----
})
export class AppModule { }
方法二。在
component
中添加类的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) {
}
}
重要提示:请不要忘记将类(class)注释为 @Injectable
这样您就可以将其注入(inject)构造函数中,即import { Injectable } from "@angular/core";
@Injectable() // class annotation as Injectable
export class MyService {
constructor() {
}
}
关于angular - NullInjectorError : No provider for class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48988513/