我正在尝试使用 Angular2 依赖注入,但收到以下错误消息:
错误 NG2003:没有适合类“PaymentService”的参数“服务”的注入令牌
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);
}
}
注意:如果我用其实现之一(PaymalPayment 或 CardPayment)替换 PaymentService 文件中的接口“Payment”,一切正常。但是那里有一个接口是很常见的情况。
- git 克隆https://github.com/karenmargaryan/di-via-interfaces-issue
- cd di-via-interfaces-issue
- npm 安装
- 服务