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

标签 angular typescript initialization

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

相关文章:

javascript - 突出显示 Angular2 中嵌套 ngFor 元素的 [class.active]

angular - 将逗号分隔的千位添加到 Angular2 中的数字输入

angular - Typescript "this"实例在类中未定义

c++ - C++03使用函数调用结果初始化多个成员?

c - C 中的字符串声明

c++ - 如何用常量成员值初始化数组成员?

javascript - p5.j​​s createCanvas 不再渲染。 ngOnInit const 未被访问

node.js - Put 方法不在后端使用 NodeJS 更新 Angular7 中的 MongoDB

javascript - Angular 2 与 TypeScript : View not updating after setting variable in response handler

typescript mocha describe 不是函数