@d78ng/file-loader
Provides Angular service to simplify file loading (for example configuration) from a local path on the server.
Getting started
Prerequisities
An existing Angular application. Angular CLI can be used to create one.
Installing
npm i -s @d78ng/file-loader
How to use
Loading a single file during application initialization:
app.module.ts:
// Define imports:
import {FileLoaderService} from '@d78ng/file-loader';
// Factory function for APP_INITIALIZER:
export function init(cfg: FileLoaderService) {
return () => new Promise(async(resolve) => {
try {
await cfg.load('/cfg/config.json', '/assets/config.json');
resolve(true);
} catch {
resolve(false);
}
});
}
//...
@NgModule({
//...
// Define the required providers:
providers: [
HttpClient,
LocalFileService,
{provide: APP_INITIALIZER, useFactory: init, deps:[LocalFileService], multi: true}
],
//...
})
(Alternatively) Loading multiple files:
app.tokens.ts:
import {InjectionToken} from '@angular/core';
import {FileLoaderService} from '../../projects/file-loader/src/lib/file-loader.service';
// Define an injection token for each of the files:
// (First file contains configuration, second file contains version info)
export const LOCAL_FILE_CFG: InjectionToken<FileLoaderService> = new InjectionToken<FileLoaderService>("local-file.cfg");
export const LOCAL_FILE_VER: InjectionToken<FileLoaderService> = new InjectionToken<FileLoaderService>("local-file.ver");
app.module.ts:
// Define imports
import {FileLoaderService} from '@d78ng/file-loader';
// Factory function for FileLoaderService creation:
export function initFLS(http: HttpClient) {
return new FileLoaderService(http);
}
// Factory function for APP_INITIALIZER:
export function init(cfg: FileLoaderService, ver: FileLoaderService) {
return () => new Promise(async(resolve) => {
try {
await Promise.all([
cfg.load('/cfg/config.json', '/assets/config.json'),
ver.load('/assets/version.json')
]);
resolve(true);
} catch {
resolve(false);
}
});
}
//...
@NgModule({
//...
// Define the required providers:
providers: [
HttpClient,
{provide: LOCAL_FILE_CFG, useFactory: initFLS, deps: [HttpClient]},
{provide: LOCAL_FILE_VER, useFactory: initFLS, deps: [HttpClient]},
{provide: APP_INITIALIZER, useFactory: init, deps:[LOCAL_FILE_CFG, LOCAL_FILE_VER], multi: true}
],
//...
})
Access the data:
app.component.ts:
export class AppComponent {
private backendUrl: string;
constructor(configService: FileLoaderService) {
this.backendUrl = configService.data.backendUrl;
}
}
Versioning
This project uses SemVer for versioning. For the versions available, see the tags on its repository.
License
This project is licensed under the MIT License - see the LICENSE.md file for details.