angular dependency injection not resolving for library component

242 Views Asked by At

it is a simple situation. In my library project called lib-a, defines 3 classes: libAModule, LibAComponent and MyService. LibAComponent has a constructor that takes MyService as a parameter. MyService is decorated with

@Injector() 

attribute.

In the Root Application's appModule, i provide that service:

providers: [MyService]

the appModule also has a constructor that takes MyService as a parameter.

When i run the app the dependency is resolved in the appModule's constructor (verified by stepping through in the debugger), however, when trying to render the LibAComponent i get the following error in the browsers console window:

Error: StaticInjectorError(AppModule)[libAComponent-> MyService]: 
  StaticInjectorError(Platform: core)[libAComponent-> MyService]: 
    NullInjectorError: No provider for MyService!

I can fix that by updating the

@Injector({provideIn: 'root'}) 

attribute on the MyService. However, theoretically it is equivalent to providing the service in the appModule as i am doing. The reason i want to do it this way is because ultimately, i want to provide the service in appModule as such:

providers: [{provide: MyService, useClass: MyExtendedService }] 

where myExtendedService is defined outside of the library project.

Can anyone figure out why i get that error when i provide the service through appModule?

1

There are 1 best solutions below

1
nircraft On

You should be using

 providers: [ MyService ]

in stead of

provider: [{provide: MyService, useClass: MyExtendedService }]