Reputation: 43
I'm trying to use Angular2 dependency injection but get the following error message:
error NG2003: No suitable injection token for parameter 'service' of class 'PaymentService'
app.module.ts - provider with factory method
@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 payment service
@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 files
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);
}
}
Note: Everything works fine if I replace the interface "Payment" in PaymentService file with one of its implementations (PaymalPayment or CardPayment). But it's a pretty common case to have an interface there.
Upvotes: 2
Views: 776
Reputation: 3116
In payment.service.ts :
Update the Constructor
//import { Inject } from '@angular/core';
constructor(@Inject(Payment) private service: Payment)
Upvotes: 2