gpt4 book ai didi

angular - 如何处理/通知用户 APP_INITIALIZER 中不可恢复的异常?

转载 作者:太空狗 更新时间:2023-10-29 16:55:17 24 4
gpt4 key购买 nike

我的 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。

最佳答案

在 main.ts 中,我以这种方式更改了 Bootstrap :

platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => {
// error should be logged into console by defaultErrorLogger, so no extra logging is necessary here
// console.log(err);
// show error to user
const errorMsgElement = document.querySelector('#errorMsgElement');
let message = 'Application initialization failed';
if (err) {
if (err.message) {
message = message + ': ' + err.message;
} else {
message = message + ': ' + err;
}
}
errorMsgElement.textContent = message;
});

任何发生的异常都会被捕获并且消息被设置到一个 html 元素中。该元素在 index.html 中的 app-root 标记中定义,例如

<app-root><div id="errorMsgElement" style="padding: 20% 0; text-align: center;"></div> 
</app-root>

如果bootstrap成功,tag的内容会被angular替换。

关于angular - 如何处理/通知用户 APP_INITIALIZER 中不可恢复的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48564687/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com