1

我正在添加带有要发出的事件的自定义错误处理程序,在错误时我想向主组件发出错误消息以在页面顶部显示它。

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
  constructor() { }
  errors: BehaviorSubject<any> = new BehaviorSubject(false);
   //errors: Subject<any> = new Subject();
  technicalError= false;
  handleError(error) {
        const httpCode = error.status;
         if (httpCode !== undefined) {
           this.errors.next(error._body);
           //this.technicalError = true;
         }else {
           console.log('Error--' + error);
           // throw error;
         }
        }

    }

主要组件.ts

@Component{
 providers: {GlobalErrorhandler}
}
export class MainComponent {

constructor(private glbError:GlobalErrorHandler){
}

onInit(){
this.glbError.errors.subscribe({
body=> {
this.technicalErrors = body;
}
});
}

showError(){
 throw new error();//consider it as http error with 400 or 403, this is sample one
}
}

在从后端收到错误时,它会触发 handleError 方法,但不会将错误消息发送到 MainComponent。

更新的问题 还在 MainModule 中添加了以下行

providers: [{provide:ErrorHandler, useClass:GlobalErrorHandler}]

4

1 回答 1

0

建议最好不要像这样暴露完整的主题对象

errors: BehaviorSubject<any> = new BehaviorSubject(false);

应该是这样的

private errorsSubejct: BehaviorSubject<any> = new BehaviorSubject(false);

get errors():Observable<any> {
    return this.errorsSubject.asObservable();
}

你能这样试试吗

this.glbError.errors.asObservable().subscribe({
body=> {
this.technicalErrors = body;
}
});

所以你的代码会是这样的,component.ts

@Component{
 providers: {GlobalErrorhandler}
}
export class MainComponent {

technicalErrors: any[];

constructor(private glbError:GlobalErrorHandler){
}

onInit(){
this.technicalErrors = [];
this.glbError.errors.asObservable().subscribe({
body=> {
this.technicalErrors = body;
}
});
}

showError(){
 throw new error();//consider it as http error with 400 or 403, this is sample one
}
}

组件.html

<div *ngFor="let err of technicalErrors">
  {{err|json}}
</div>
于 2018-03-19T15:33:11.547 回答