Angular2 依存性注入を使用しようとしていますが、次のエラー メッセージが表示されます。
エラー NG2003: クラス 'PaymentService' のパラメーター 'service' に適切なインジェクション トークンがありません
app.module.ts - ファクトリ メソッドを持つプロバイダー
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [
PaypalPayment,
CardPayment,
{
provide: PaymentService,
useFactory: () => {
return new PaymentService(new PaypalPayment());
}
}
],
bootstrap: [AppComponent]
})
export class AppModule {
}
payment.service.ts - 注入可能な支払いサービス
@Injectable()
export class PaymentService {
constructor(private service: Payment) {
}
pay(amount: number) {
console.log('Payment Service -> pay(...) is running');
this.service.pay(amount);
}
}
payment.interface.ts、card-payment.ts、paypal-payment.tsファイル
export interface Payment {
pay(amount: number);
}
@Injectable()
export class CardPayment implements Payment {
pay(amount: number) {
console.log('Paid by card. Amount=', amount);
}
}
@Injectable()
export class PaypalPayment implements Payment {
pay(amount: number) {
console.log('Paid via Paypal. Amount=', amount);
}
}
注: PaymentService ファイルのインターフェイス「Payment」をその実装の 1 つ (PaymalPayment または CardPayment) に置き換えると、すべて正常に動作します。しかし、そこにインターフェースがあるのはかなり一般的なケースです。
- git クローンhttps://github.com/karenmargaryan/di-via-interfaces-issue
- cd di-via-interfaces-issue
- npm インストール
- サーブしない