Karen Margaryan
Karen Margaryan

Reputation: 43

Angular2 Dependency Injection by Factory Method using Interface

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.

The full source code is here

  1. git clone https://github.com/karenmargaryan/di-via-interfaces-issue
  2. cd di-via-interfaces-issue
  3. npm install
  4. ng serve

Upvotes: 2

Views: 776

Answers (1)

Useme Alehosaini
Useme Alehosaini

Reputation: 3116

In payment.service.ts :

Update the Constructor

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

constructor(@Inject(Payment) private service: Payment)

Upvotes: 2

Related Questions