Angular 4:自定义errorHandler,Subject或BehaviorSubject不起作用

时间:2018-03-19 15:27:39

标签: angular angular-errorhandler

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

@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;
         }
        }

    }

主component.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}]

1 个答案:

答案 0 :(得分: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
}
}

component.html

<div *ngFor="let err of technicalErrors">
  {{err|json}}
</div>