Reputation: 1791
I have been considering the best approach for "bootstrapping" an angular (v6) application. By bootstrapping I mean getting the initial config my app may need from a static json file on the server, and perhaps making 1 or 2 other http requests for various pieces of data that are needed before triggering the cascade of component creation etc.
Currently our approach is to do everything in the AppComponent, and wrapping everything in the template of the app component in something like
<div *ngIf="isBootstrapping">...show a spinner here...</div>
<div *ngIf="!isBootstrapping">...put main site contents here...</div>
And then just toggle isBootstrapping in the app component when the various requests have completed and I have all the data I deem necessary. This feels like a dirty approach to me though, and I would assume angular has something a bit more elegant.
Should I rather be doing this in a provider with a useFactory option?
Upvotes: 2
Views: 197
Reputation: 998
Angular does have something more elegant. It's the APP_INITIALIZER
token. It would look something like:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { AppComponent } from './app.component';
function initApp(http: HttpClient) {
return () => {
return http.get('https://link.to/configuration.json')
.pipe(
// do your configuration stuff
)
.toPromise();
};
}
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [
{
provide: APP_INITIALIZER,
useFactory: initApp,
multi: true,
deps: [HttpClient]
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
It will run the initApp
logic and wait for it to be done before boostrapping the AppComponent
.
Upvotes: 1