Ng Boot
Boot(Initialize) services before loading the application with Angular.
Table of Contents:
Installation
npm install @greg-md/ng-boot --save
Integration
1. Create a boot strategy;
Let say we want to boot the application after 5 seconds.
For that we create a timeout boot in ./timeout.boot.ts
.
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {BootStrategy} from '@greg-md/ng-boot';
@Injectable()
export class TimeoutBoot implements BootStrategy {
readonly key = 'timeout';
boot() {
return Observable.empty().delay(5000);
}
}
2. Import boot module and initialise the strategy;
import {BrowserModule} from '@angular/platform-browser';
import {NgModule, APP_INITIALIZER} from '@angular/core';
// 1. Import BootModule, BootService and TimeoutBoot;
import {BootModule, BootService} from '@greg-md/ng-boot';
import {TimeoutBoot} from './timeout.boot.ts';
import {AppComponent} from './app.component';
// 2. Create and export provider factory that will boot the TimeoutBoot;
export function timeoutFactory(service: BootService, strategy: TimeoutBoot) {
return service.initialize(strategy);
}
@NgModule({
imports: [
BrowserModule,
// 3. Register BootModule with it's providers;
BootModule.forRoot(),
],
providers: [
// 4. Register TimeoutBoot and initialize its factory.
TimeoutBoot,
{
provide: APP_INITIALIZER,
useFactory: timeoutFactory,
deps: [ BootService, TimeoutBoot ],
multi: true,
},
],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
3. Using in routes.
Use BootResolve
in a root route to prevent routes to be loaded before all strategies are booted.
import {Routes} from '@angular/router';
// 1. Import BootResolve;
import { BootResolve } from '@greg-md/ng-boot';
export const routes: Routes = [
{
path: '',
resolve: {
// 2. Register BootResolve in the root route.
boot: BootResolve,
},
// 3. Register app routes in the root route children.
children: [
{ path: '', loadChildren: './+home/home.module#HomeModule' },
{ path: 'about', loadChildren: './+about/about.module#AboutModule' },
]
},
];
Boot Service
BootService
provides you some useful methods for you.
initialize
Initialize a BootStrategy
for APP_INITIALIZER
factory.
initialize(strategy: BootStrategy, stopOnFail: boolean = false): Promise<any>
reboot
If some of your boot strategies failed, you can retry rebooting them.
reboot(): Observable<any>
resolve
Resolve all boot strategies.
resolve(): Observable<Object>
License
MIT © Grigorii Duca