Angular 5自定义错误处理程序:显示错误消息

时间:2018-01-29 09:58:52

标签: javascript html angular error-handling angular5

我正在尝试为Angular 5创建一个错误处理程序。如果通过我的CustomErrorHandler触发了错误,则应该更新前端。 问题是变量更新后没有任何变化。

错误handler.service.ts

import {ErrorHandler, Injectable} from '@angular/core';
import {Subject} from "rxjs/Subject";

@Injectable()
export class CustomErrorHandler implements ErrorHandler {
    message: String = "";
    isVisible: boolean = false;

    visibilityChange: Subject<boolean> = new Subject<boolean>();

    constructor() {
        this.visibilityChange.subscribe((value) => {
            this.isVisible = value
        });
    }

    handleError(error) {
        console.error(error);
        this.message = "ERROR: " + error.toString();
        this.visibilityChange.next(true);
    }
}

错误message.component.ts

import {Component} from '@angular/core';
import {CustomErrorHandler} from "../../../services/error-handler.service";

@Component({
    selector: 'app-error-message',
    templateUrl: './error-message.html',
})

export class ErrorMessageComponent {
    public message: String = "";
    public isVisible: boolean = false;

    constructor(private customErrorHandler: CustomErrorHandler) {
        this.isVisible = customErrorHandler.isVisible;
    }
}

错误handler.html

<div class="alert alert-danger" id="app-error" *ngIf="isVisible">
    {{message}}
</div>

app.html

<app-nav></app-nav>
<div class="container">
    <div class="jumbotron">
        <app-error-message></app-error-message>
        <app-info-message></app-info-message>
        <router-outlet></router-outlet>
    </div>
</div>
<app-footer></app-footer>

app.module.ts

@NgModule({
    declarations: [
        AppComponent,
        ErrorMessageComponent,
        .....
    ],
    imports: [
        BrowserModule,
        FormsModule,
        HttpClientModule,
        AngularFontAwesomeModule,
        routing
    ],
    providers: [
        UserService,
        {
            provide: ErrorHandler,
            useClass: CustomErrorHandler
        },
        CustomErrorHandler
    ],
    bootstrap: [AppComponent]
})
export class AppModule {
}

有人知道我做错了吗?

1 个答案:

答案 0 :(得分:0)

对于rxjs订阅,您可能必须使用changedetection。

    constructor(private changeDetection: ChangeDetectorRef) {
    this.visibilityChange.subscribe((value) => {
        this.isVisible = value; this.changeDetection.detectChanges();
    });
}