gpt4 book ai didi

angular - NullInjectorError : No provider for class

转载 作者:行者123 更新时间:2023-12-03 12:37:37 27 4
gpt4 key购买 nike

我在组件类中将类作为依赖注入(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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com