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.

cmlonder
  • 2,370
  • 23
  • 35
Akash
  • 4,412
  • 4
  • 30
  • 48

1 Answers1

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)
   }
}
Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79