A complete working solution using Angular 11. Assuming you generated a library named library1
using the command ng generate library library1
.
AppModule file
// Your other imports ...
import { Library1Module } from 'library1';
import { environment } from 'src/environments/environment';
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
// Pass the data you want to share with your library. Here we will pass 'apiUrl'.
Library1Module.forRoot({ apiUrl: environment.apiUrl }),
AppRoutingModule
]
})
export class AppModule { }
library1.module.ts ('Library1' module main file):
import { ModuleWithProviders, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Configurations } from './configurations';
import { Library1Component } from './library1.component';
@NgModule({
declarations: [Library1Component],
imports: [CommonModule],
exports: [Library1Component]
})
export class Library1Module {
// Create this static method in the library module.
public static forRoot(config: Configurations): ModuleWithProviders<Library1Module> {
return {
ngModule: Library1Module,
providers: [
{ provide: Configurations, useValue: config }
]
};
}
}
configurations.ts (Declare this class inside 'projects\library1\src\lib' folder). Declare all the configurations you need to get from the 'environment' file.
export class Configurations {
public apiUrl: string;
constructor() {
this.apiUrl = '';
}
}
library1.service.ts ('Library1Service' will receive the config object).
import { Injectable, Optional } from '@angular/core';
import { Configurations } from './configurations';
@Injectable({
providedIn: 'root'
})
export class Library1Service {
private _apiUrl = 'No value';
constructor(@Optional() config?: Configurations) {
if (config) {
this._apiUrl = config.apiUrl;
}
}
get apiUrl() {
return this._apiUrl;
}
}
library1.component.ts (Library1 Component that uses the configuration data).
import { Component } from '@angular/core';
import { Library1Service } from '../public-api';
@Component({
selector: 'lib-library1',
template: `
<p>
This component inside "library1" library and reads the values from "environment.ts" file.
</p>
<h1>API URL : {{apiUrl}}</h1>`
})
export class Library1Component {
apiUrl = '';
constructor(library1Service: Library1Service) {
this.apiUrl = library1Service.apiUrl;
}
}
app.component.ts (Confirm that the URL already passed to your library by using the library1 component).
.......
<lib-library1></lib-library1>
.......