NullInjectorError:类的没有提供程序

Was*_*siF 1 angular2-services angular

NullInjectorError:类形成没有提供者!

// Component
import { Formation } from '../../Models/Formation';

@Component({
  selector: 'app-formation',
  templateUrl: './formation.component.html',
  styleUrls: ['./formation.component.scss'],
})
export class FormationComponent {
  constructor(private formation: Formation) { }
}

// Model Class
export class Formation {
}
Run Code Online (Sandbox Code Playgroud)

有什么问题吗?

Was*_*siF 6

角度6+

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class Formation {

    constructor() {
    }
}
Run Code Online (Sandbox Code Playgroud)

角度5

1.app.module.ts的提供者中添加类

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [
    Formation // added class in the providers
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)

2. 在添加类componentprovider

@Component({
  selector: 'app-formation',
  templateUrl: './formation.component.html',
  styleUrls: ['./formation.component.scss'],
  providers: [
    Formation // added class in the providers
  ]
})
export class FormationComponent {

  constructor(private formation: Formation) {
  }

}
Run Code Online (Sandbox Code Playgroud)

并在课堂上注释为 @Injectable

import { Injectable } from "@angular/core";

@Injectable() // class annotation as Injectable
export class Formation {

    constructor() {
    }
}
Run Code Online (Sandbox Code Playgroud)