0

I have an issue with inject service dynamically.

// NPM Package 1:
@Injectable() 
export abstract class BaseService { ... }
@Injectable()
export class ServiceA extends BaseService { ... }
@Injectable()
export class ServiceB extends BaseService { ... }

// NPM Package 2:
// nav.module.ts
@NgModule({
    imports: [ ... ],
    declarations: [
        NavComponent
    ],
    exports: [
        NavComponent
    ],
    providers: []
})
export class NavModule { }

// nav.component.ts
@Component({
    selector: 'app-nav',
    ...
})
export class NavComponent {
    constructor(private baseService: BaseService) { ... }
}


// main project
// app.module.ts:
@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        NavModule
    ],
    providers: [
        {provide: BaseService, useClass: ServiceB }
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

// app.component.ts
@Component({ ... })
export class AppComponent implements OnInit {
    constructor(private baseService: BaseService) { }
    ...
}

// app.component.html
<app-nav></app-nav>

When running the project, I got the error:

Error: No provider for BaseService!

The service is not injected into the NPM package 2.

If I directly include the code for NPM package 2 in the main project, there is no problem. The BaseService will get injected as ServiceB.

Any idea what might be wrong? I used ng-packagr (https://github.com/dherges/ng-packagr) to generate NPM package.

user3616544
  • 1,023
  • 1
  • 9
  • 31

1 Answers1

0

NavModule is getting imported by AppModule, not the other way around. So you should either

  • change the dependency direction and make NavModule import Appodule
  • Put NavComponent into AppModule
  • make NavModule provide the service as well
  • make a SharedModule that provides the service and make NavModule and AppModule both import from it.

As NavModule sounds like a part of Ui-Library (where all components are responsible only for displaying things but not routing or store acess etc), I recommend checking if it really needs a "BaseService" and if that is a Ui-related functionality, to provide the service only for the Ui-Library

Phil
  • 7,065
  • 8
  • 49
  • 91