【问题标题】:angular 2 - show error message for any exception角度 2 - 显示任何异常的错误消息
【发布时间】:2016-12-23 08:08:58
【问题描述】:

我正在尝试在 Angular 2(打字稿)中执行以下操作:对于每个错误(尤其是来自后端服务器的错误)-向用户呈现错误(在 UI 中)-在主要组件中(主要是因为我不想在每个组件中编写相同的代码)。

这是一种简单的方法吗?我想我需要的是一种在主要组件中设置“错误”成员的方法?如果我重写 ExceptionHandler 怎么办?

谢谢, 帕维尔。

【问题讨论】:

  • 请参阅stackoverflow.com/questions/38882969/…angular.io/docs/ts/latest/api/core/index/… 您应该知道,如果不在本地捕获异常可能会使您的组件处于未定义状态。之后您可能需要显式调用更改检测。参见例如stackoverflow.com/questions/37793276/…
  • 您好 Günter,我的问题是如何让 ExceptionHandler 更改主应用程序组件中的某些状态(以在 UI 中显示错误消息)?
  • 您可以使用共享服务,从异常处理程序更新状态或使用可观察对象和组件根据来自该服务的信息更新 DOM(显示错误信息)发出事件。跨度>
  • 您好 Günter,如果我理解正确,您建议:在 ExceptionHandler - 调用 MyService.setErrorState(true),然后在主组件中添加调用 MyService.getErrorState() 的 ngif。但是移到下一页时谁会调用 MyService.setErrorState(false)?
  • 这取决于您的要求。也许您想等到用户单击“关闭”或只是超时,以便消息在 10 秒后消失,...

标签: angular error-handling


【解决方案1】:
  1. 在共享目录中创建 NotificationService

    import { Injectable } from '@angular/core';
    import { Message } from 'primeng/primeng';
    
    @Injectable()
    export class NotificationService {
        message: Message[];
    
        constructor() {
            this.message = [];
        }
    
        success(detail: string, summary?: string): void {
            this.message.push({
                severity: 'success', summary: summary, detail: detail
            });
        }
    
        info(detail: string, summary?: string): void {
            this.message.push({
                severity: 'info', summary: summary, detail: detail
            });
        }
    
        warning(detail: string, summary?: string): void {
            this.message.push({
                severity: 'warn', summary: summary, detail: detail
            });
        }
    
        error(detail: string, summary?: string): void {
            this.message.push({
                severity: 'error', summary: summary, detail: detail
            });
        }
    }
    
  2. 在共享目录中创建一个自定义的 ExceptionHandler(RC 6 中的 ErrorHandler)

    import { ErrorHandler, Inject } from '@angular/core';
    import { NotificationService } from './notification.service';
    
    
    export class CustomErrorHandler implements ErrorHandler {
    
        constructor(@Inject(NotificationService) private notificationService: NotificationService) {
        }
    
        handleError(error: any): void {
            this.showErrorInConsole(error);
            setTimeout(() => 
                this.notificationService.error(error.json().Message), 1);
        }
    
        private showErrorInConsole(error: any) :void {
            if (console && console.group && console.error) {
                console.group("Error Log");
                console.error(error);
                console.error(error.message);
                console.error(error.stack);
                console.groupEnd();
            }
        }
    }
    
  3. 更新 AppModule 以覆盖默认错误处理程序

    import { GrowlModule } from 'primeng/primeng';
    ...
    import { NotificationService } from './shared/notification.service';
    import { CustomErrorHandler } from './shared/custom-error-handler';
    
    @NgModule({
        imports: [
            ...,
            GrowlModule // prime ng notification
        ],
        declarations: [
            ...
        ],
        providers: [
            ...,
            NotificationService, // added
            { provide: ErrorHandler, useClass: CustomErrorHandler } // overrride default error handler
        ],
        bootstrap: [AppComponent]
    })
    export class AppModule { }
    
  4. 终于在 AppComponent 中:

    import { Component } from '@angular/core';
    import { Message } from 'primeng/primeng';
    import { NotificationService } from './shared/notification.service';
    
    
    @Component({
        selector: 'my-app',
        template: `
            <p-growl [value]="getMessages()"></p-growl>
        `
    })
    export class AppComponent{
        constructor(private notification: NotificationService) {
        }
    
        getMessages(): Message[] {
            return this.notification.message;
        }
    }
    

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-05
  • 1970-01-01
  • 2018-03-08
相关资源
最近更新 更多