1

I have an angular library which calls backend java API. I want the ability to configure the API URL in the library through angular application module where I import the library.

I have tried having forRoot() in the library but my application gives below runtime error because my application modules are loaded lazily -

ERROR Error: "StaticInjectorError[FeatureComponent -> Service]: StaticInjectorError(AppModule)[HttpClient]: StaticInjectorError(Platform: core)[HttpClient]: NullInjectorError: No provider for HttpClient!"

Below is the code library snippet -

 export class LibModule { constructor(injector: Injector) { setLibInjector(injector); } public static forRoot(environment: any): ModuleWithProviders { return { ngModule: LibModule, providers: [ { provide: 'appEnv', // use InjectionToken useValue: environment } ] }; } } 

Below is one of the module in my app where I import the library -

@NgModule({ declarations: [ ], imports: [ LibModule.forChild({baseUrl: '/configuration/'}), ], entryComponents: [], providers: [] }) export class FeatureModule { } 

Note I want to know how to write a library to accept configuration parameters from any kind of angular module (eagerly or lazily loaded). Someone has marked the question as duplicate.

2
  • Possible duplicate of No provider for HttpClient Commented Apr 15, 2019 at 10:46
  • 1
    The question is not duplicate. Please check again @PrashantPimpale Commented Apr 15, 2019 at 10:59

1 Answer 1

1

Suppose in your LibModule you want to use environment in XyzService,

App.module.ts

 imports: [ BrowserModule, LibModule.forRoot({ environment: environment }) ] 

LibModule.module.ts

export class LibModule{ static forRoot(environment): ModuleWithProviders { console.log(environment); return { ngModule: LibModule, providers: [XyzService,{provide: 'config', useValue: environment}] }; } } 

XyzService.service :

export class XyzService{ constructor(@Inject('config') private config:any) { console.log(config) } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.