During the initialization of my Angular5 app, it retrieves a configuration file from the backend using APP_INITIALIZER. If the app fails to load this configuration file, I want to display a message to the user indicating the issue.
providers: [ AppConfig,
{ provide: APP_INITIALIZER, useFactory: (config: AppConfig) => () => config.load(), deps: [AppConfig], multi: true },
{ provide: LocationStrategy, useClass: HashLocationStrategy},
{ provide: ErrorHandler, useClass: GlobalErrorHandler }]
For the AppConfig
class to function properly, it needs to fetch the configuration file from the backend service before the app can fully load:
@Injectable()
export class AppConfig {
private config: Object = null;
constructor(private http: HttpClient) {}
public getConfig(key: any) {
return this.config[key];
}
public load() {
return new Promise((resolve, reject) => {
this.http.get(environment.serviceUrl + 'config/config')
.catch((error: any) => {
return Observable.throw(error || 'Server error');
})
.subscribe((responseData) => {
this.config = responseData;
this.config['service_endpoint'] = environment.serviceUrl;
resolve(true);
});
});
}
}
Global Exception handler:
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
constructor( private messageService: MessageService) { }
handleError(error) {
// The AppConfig exception cannot be displayed with the growl message since the growl component is within the AppComponent
this.messageService.add({severity: 'error', summary: 'Exception', detail: `Global Exception Handler: ${error.message}`});
throw error;
}
}
If the app fails to load the config file, it triggers an exception which is caught and handled by the global exception handler resulting in an uncaught HTTPErrorResponse in the console.log(), while the loading spinner continues indefinitely.
Since the AppComponent
is not loaded (which is expected as the app relies on the configuration), and my message/growl Component is a subcomponent of the AppComponent
, I am unable to display a message to the user.
Is it possible to show a message on the index.html
page at this stage? I prefer not to redirect the user to a different .html page as they would simply refresh on the error.html page.