NullInjectorError: No provider for class
NullInjectorError: No provider for class
我在组件 class 中注入了 class 作为依赖注入,但出现错误
NullInjectorError: No provider for class
这是我的代码:
// Component
import { Formation } from './Models/Formation';
export class FormationComponent {
constructor(private formation: Formation) { }
}
// Model Class
export class Formation {
}
会有什么问题?
Angular6+
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class MyService {
constructor() {
}
}
Angular 5
方法一.在app.module.ts
的供应商中添加class
@NgModule({
// ----
providers: [
MyService // added class in the providers
]
// ----
})
export class AppModule { }
方法二
在 component
的 provider
中添加 class
@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
以便您可以将其注入构造函数,即
import { Injectable } from "@angular/core";
@Injectable() // class annotation as Injectable
export class MyService {
constructor() {
}
}
我遇到了同样的问题,解决方案是在应用程序模块中添加服务引用。一旦包含在内,您就可以轻松摆脱它。
注意:Angular 4 个是相同的解决方案。已检查
我在组件 class 中注入了 class 作为依赖注入,但出现错误
NullInjectorError: No provider for class
这是我的代码:
// Component
import { Formation } from './Models/Formation';
export class FormationComponent {
constructor(private formation: Formation) { }
}
// Model Class
export class Formation {
}
会有什么问题?
Angular6+
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class MyService {
constructor() {
}
}
Angular 5
方法一.在app.module.ts
的供应商中添加class
@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
以便您可以将其注入构造函数,即
import { Injectable } from "@angular/core";
@Injectable() // class annotation as Injectable
export class MyService {
constructor() {
}
}
我遇到了同样的问题,解决方案是在应用程序模块中添加服务引用。一旦包含在内,您就可以轻松摆脱它。
注意:Angular 4 个是相同的解决方案。已检查