Malik Kashmiri
Malik Kashmiri

Reputation: 5851

How to show Error Page with Message in Angular 2

detail

I am trying to make an error page when ever the false routing detect or unauthorized access or other kind of exception occurs I want to redirect to the page and want to show respected error on this page with my angular application. now I am doing it just by passing an error message in query string. But I want to pass different exception message without query string How I can achieve it. and also give suggestion what is the best way to do it.

Error Component

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
];

Error

when some thing went wrong I call this message

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

Image

enter image description here

Upvotes: 1

Views: 7758

Answers (1)

simdevmon
simdevmon

Reputation: 693

I solved this issue with a shared service, using a BehaviorSubject to show the last value.

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

This service is only defined in the app module.

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

To set the error message simply inject the service and set the message:

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

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

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

The error component would use the service like this:

import { Component, OnDestroy } from '@angular/core';
import { ErrorService } from './error.service';
import { Subscription } from 'rxjs/Subscription';

@Component({
    templateUrl: 'app/error/error.component.html'
})
export class ErrorComponent implements OnDestroy {

    message: string = '';
    subscription: Subscription;

    constructor(private errorService: ErrorService) {
        this.subscription = this.errorService.update$.subscribe(
            message => {
                this.message = message;
            });
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}

Upvotes: 6

Related Questions