1

我正在尝试使用 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”,一切正常。但是那里有一个接口是很常见的情况。

完整的源代码在这里

  1. git 克隆https://github.com/karenmargaryan/di-via-interfaces-issue
  2. cd di-via-interfaces-issue
  3. npm 安装
  4. 服务
4

1 回答 1

0

payment.service.ts中:

更新构造函数

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

constructor(@Inject(Payment) private service: Payment)
于 2020-03-28T13:10:55.627 回答