angular - NullInjectorError : No provider for class

标签 angular angular2-services

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

相关文章:

angular - 使用 SSL 证书在 apache2 上部署 Angular

angular - 如何从 component.ts 文件中的 Angular 2 中的 json 响应获取键/值对

angular - 在不订阅的情况下使用 Angular 2 http.post?还是我想错了?

javascript - 在订阅功能之外无法访问数据

angular - 无法从 BackdropClick 关闭 Angular Material Cdkoverlay

node.js - 将 nbind 与 Angular 5 和 TypeScript 一起使用

angular - 未捕获的类型错误 : Cannot read property 'core' of undefined

angular - 是否可以为 mat-tree 设置动画? ( Angular Material )

Angular 2 : which is the best way to make multiple sync calls with Observables?

angular - 在不共享同一父组件的子组件之间共享 Angular 2 服务