Vous pouvez utiliser APP_INITIALIZER pour appeler un service méthode de bootstrap. Vous aurez besoin de définir un provider
dans votre AppModule
.
Voici un exemple de comment faire cela.
StartupService (démarrage.service.ts)
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class StartupService {
private _startupData: any;
constructor(private http: Http) { }
// This is the method you want to call at bootstrap
// Important: It should return a Promise
load(): Promise<any> {
this._startupData = null;
return this.http
.get('REST_API_URL')
.map((res: Response) => res.json())
.toPromise()
.then((data: any) => this._startupData = data)
.catch((err: any) => Promise.resolve());
}
get startupData(): any {
return this._startupData;
}
}
AppModule (app.le module.ts)
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { StartupService } from './startup.service';
// ...
// Other imports that you may require
// ...
export function startupServiceFactory(startupService: StartupService): Function {
return () => startupService.load();
}
@NgModule({
declarations: [
AppComponent,
// ...
// Other components & directives
],
imports: [
BrowserModule,
// ..
// Other modules
],
providers: [
StartupService,
{
// Provider for APP_INITIALIZER
provide: APP_INITIALIZER,
useFactory: startupServiceFactory,
deps: [StartupService],
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
EDIT (Comment gérer l'échec de démarrage du service):
AppComponent (app.composante.ts)
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { StartupService } from './startup.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
constructor(private router: Router, private startup: StartupService ) { }
ngOnInit() {
// If there is no startup data received (maybe an error!)
// navigate to error route
if (!this.startup.startupData) {
this.router.navigate(['error'], { replaceUrl: true });
}
}
}