如何在Angular 2中显示带消息的错误页面

时间:2016-08-19 07:47:33

标签: angular typescript exception-handling

细节

我正在尝试制作错误页面,以防错误路由检测或未经授权的访问或其他类型的异常发生我想重定向到页面并希望在我的角度应用程序的此页面上显示受尊重的错误。现在我只是通过在查询字符串中传递错误消息来做到这一点。但是我希望在没有查询字符串的情况下传递不同的异常消息我怎么能实现它。并提出建议是什么是最好的方法。

错误组件

import { Inject } from '@angular/core';
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Router } from '@angular/router';
import 'rxjs/add/operator/map';

@Component({
    selector: 'error',
    template: `
    <h2>Error</h2>
    <h4> {{ errMessage | async }} </h4>
    `
})
export class ErrorComponent implements OnInit {

    errMessage: Observable<string>;

    constructor(@Inject(Router) private router: Router) { }

    ngOnInit() {

        this.errMessage = this.router.routerState.queryParams
            .map(params => params['errMsg'] || '');

    }
}

App.Route

import { provideRouter, RouterConfig } from '@angular/router';

import { AccountComponent } from './components/account/account.component';
import { PageNotFoundComponent } from './components/not-found.component';
import { userRoutes } from './components/user/user.routes';

import { AuthGuard }          from './services/auth/auth-guard.service';
import { AuthService }        from './services/auth/auth.service';

import { loginRoutes,
    authProviders }      from './components/account/account.routes';

import { ErrorComponent } from './components/error.component';
import { approvalRoutes } from './components/approval/approval.routes';

import { CanDeactivateGuard } from './services/auth/can-deactivate-guard.service';
import { AppComponent } from './components/app.component';

export const routes: RouterConfig = [      
    ...loginRoutes,
    ...userRoutes,
    ...approvalRoutes,
    { path: 'error', component: ErrorComponent},
    { path: '**', component: PageNotFoundComponent }
];

export const APP_ROUTER_PROVIDERS = [
    provideRouter(routes),
    authProviders,
    CanDeactivateGuard
];

错误

当出现问题时我会将此消息称为

public handleError(msg) {        
    let errorData = msg.json();
    let navigationExtras = { queryParams: { 'errMsg': errorData.Message }           
};

图像

{{3}}

1 个答案:

答案 0 :(得分:5)

我用共享服务解决了这个问题,使用BehaviorSubject显示最后一个值。

<div class="form-group">
    <label>Date of Birth</label>
    <input type="text" class="form-control" id="dteDoB">
</div>

此服务仅在应用模块中定义。

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class ErrorService {

    private updateSubject: BehaviorSubject<string> = new BehaviorSubject<string>('');

    update$: Observable<string> = this.updateSubject.asObservable();

    updateMessage(message: string) {        
        this.updateSubject.next(message);
    }
}

要设置错误消息,只需注入服务并设置消息:

@NgModule({
    providers: [
        ErrorService,
        ...
    ],
    ...
})

错误组件将使用如下服务:

@Component({
   ...
})
export class LayoutComponent {

    constructor(private errorService: ErrorService,
    private router: Router) {
    }

    processError() {
        this.errorService.updateMessage('Custom error message');
        this.router.navigate(['error']);
    }
}