3

I want to make an AJAX request before calling the bootstrap method in Angular 2 to bootstrap the application on page load.

Are there any hooks I can listen for to do this using Angular? I know I could wrap it in a vanilla javascript ajax request but I thought there maybe a standard way to do this with Angular 2. I need to get a configuration file from a server before I spin up the Angular 2 App.

Graham
  • 7,431
  • 18
  • 59
  • 84
HomeBrew
  • 849
  • 2
  • 12
  • 25
  • What's the purpose you want this? Don't you want Angular do display anything? It would be more efficient when Angular can initialize itself while the browser is idling while it waits for the server to respond. – Günter Zöchbauer Feb 10 '16 at 06:39
  • A similar question and an repeatedly mentioned http://stackoverflow.com/questions/34731869/wait-for-angular-2-to-load-resolve-model-before-rendering-view-template. – Günter Zöchbauer Feb 10 '16 at 06:45
  • I have a configuration object that is returned from a server. The object contains feature flags that tell components what they should show and hide for example. On first page load I would like to have this configuration before the components start to load themselves. At the moment if I do it in the App component it is too late but I'm still looking into it. – HomeBrew Feb 10 '16 at 06:48
  • 2
    You could just wrap the template content of your `AppComponent` with a big `ngIf` and when the config arrives toggle the bound flag. – Günter Zöchbauer Feb 10 '16 at 06:53
  • Thanks I like that. That should solve it although I was hoping for some type of Angular based option to do this. Ill do this for now. – HomeBrew Feb 10 '16 at 06:59

1 Answers1

2

As far as I know Angular doesn't provide a special hook for this use case.
A simple "workaround" is to just wrap the content of the template of the root component with an ngIf:

@Component({
  selector: 'my-app',
  template: `
<div *ngIf="_config">
  ...
</div>`
...
)}
export class MyApp {
  private _config;
  constructor(configService:ConfigService) {
    configService.change.subscribe(value) => {
      this.config = value;
    });
  }
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567