Reputation: 2272
I've found how to call a service before the root component loads. But I can't find a way to keep the whole app waiting until the service successfully finishes its job. In other words, how to make it a synchronous call. The service is loading essential setting through AJAX, and I have to hold the application from starting until the call finishes.
Adding *ngIf
to the router-outlet
doesn't work, it causes an error.
Blocking routes with CanActivate
will stop the views from loading, but I then have to define a loader screen and call the appropriate route from code when the promise is fulfilled. It's not very elegant.
Is there a way to tell Angular to STFU until a certain value is true
?
Upvotes: 2
Views: 1765
Reputation: 419
Not sure how you are using the APP_INITIALIZER, but I assume you have setup a factory function for the provider. If you make sure that function returns the promise of your API call made by your service the application initialization will be blocked until the promise is resolved.
E.g. create a file called app.initializer.ts
import { FactoryProvider, APP_INITIALIZER } from '@angular/core';
import { MyDataService } from './core/my-data.service';
export function initialAppSetup(provider: MyDataService) {
// MyDataService's getInitialData must return a promise
return () => provider.getInitialData()
}
export const ApplicationSetupProvider: FactoryProvider = {
provide: APP_INITIALIZER,
useFactory: initialAppSetup,
deps: [MyDataService],
multi: true
}
In your app.module.ts
import the ApplicationSetupProvider
import { ApplicationSetupProvider } from './app.initializer';
and add it to the providers array
providers: [ AuthorizationSetupProvider ],
Upvotes: 2