【发布时间】:2019-05-07 19:04:52
【问题描述】:
我的 Angular5 应用在应用初始化 (APP_INITIALIZER) 期间从后端加载配置文件。由于没有它就无法运行应用程序,因此我的目标是向用户显示无法加载配置的消息。
providers: [ AppConfig,
{ provide: APP_INITIALIZER, useFactory: (config: AppConfig) => () => config.load(), deps: [AppConfig], multi: true },
{ provide: LocationStrategy, useClass: HashLocationStrategy},
{ provide: ErrorHandler, useClass: GlobalErrorHandler }]
AppConfig 类应在应用加载之前从后端服务加载配置文件:
@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);
});
});
}
}
全局异常处理程序:
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
constructor( private messageService: MessageService) { }
handleError(error) {
// the AppConfig exception cannot be shown 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;
}
}
如果无法加载配置文件,则会在全局异常处理程序中抛出、捕获并重新抛出异常(console.log() 中未捕获的 HTTPErrorResponse),并且加载微调器将永远挂起)
由于AppComponent 没有被加载(这没关系,因为没有配置就无法使用应用程序)并且我的消息/“咆哮”组件是AppComponent 的子组件,我无法显示给用户的消息。
有没有办法在这个阶段在index.html 页面中显示消息?我不想将用户重定向到与 index.html 不同的 .html 页面,因为用户将在 error.html 上重新加载/f5。
【问题讨论】:
标签: angular typescript initialization