1

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) に置き換えると、すべて正常に動作します。しかし、そこにインターフェースがあるのはかなり一般的なケースです。

完全なソースコードはこちら

  1. git クローンhttps://github.com/karenmargaryan/di-via-interfaces-issue
  2. cd di-via-interfaces-issue
  3. npm インストール
  4. サーブしない
4

1 に答える 1