如何在angular中创建全局错误页面?

时间:2018-06-28 06:14:04

标签: angular angular-http-interceptors


我用angular 6版本编写了简单的示例。
我将globalErrorHandler用于错误情况。
我在登录操作之后和数据加载到表之前使用了加载器。
一切都很好。
如果将数据加载到表时出错,会发生什么?
如何解决此问题?如何为错误案例创建全局错误页面?
在我的示例中,我遇到了错误,即每次加载程序都无法运行。

应用程序模块

 import { BrowserModule } from '@angular/platform-browser';
    import {ErrorHandler, NgModule} from '@angular/core';
    import { RouterModule, Route } from '@angular/router';
    import {HTTP_INTERCEPTORS, HttpClientModule} from '@angular/common/http';

    import { AppComponent } from './app.component';
    import { LoginComponent } from './login/login.component';
    import { HeaderComponent } from './header/header.component';
    import {PaymentComponent} from './payment/payment.component';
    import {AuthService} from './services/auth.service';
    import {AuthGuard} from './services/auth.guard';
    import {AuthInterceptor} from './services/auth.interceptor';
    import {ExceptionHandleService} from './services/exception-handle.service';
    import {GlobalExceptionHandle} from './models/global-exception-handle';
    import {PaymentService} from './services/payment.service';
    import { NgProgressModule} from 'ngx-progressbar';
    import {HttpModule} from '@angular/http';

    const routeConfig: Route[] = [
      {
        path: 'payments',
        component: PaymentComponent,
        canActivate: [AuthGuard]
      },
      {
        path: 'login',
        component: LoginComponent
      }
    ]
    @NgModule({
      declarations: [
        AppComponent,
        LoginComponent,
        HeaderComponent,
        PaymentComponent
      ],
      imports: [
        BrowserModule,
        RouterModule.forRoot(routeConfig),
        HttpClientModule,
        NgProgressModule,
        HttpModule
      ],
      providers: [ AuthService, AuthGuard, PaymentService, {provide : HTTP_INTERCEPTORS, useClass : AuthInterceptor, multi: true},
        ExceptionHandleService, {provide: ErrorHandler, useClass: GlobalExceptionHandle}],
      bootstrap: [AppComponent]
    })
    export class AppModule { }

login.component.ts

import { Component, OnInit } from '@angular/core';
import {AuthService} from '../services/auth.service';
import {Router} from '@angular/router';
import {LoaderService} from '../services/loader.service';
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  constructor(private auth: AuthService, private router: Router, public loaderService: LoaderService ) { }

  ngOnInit() {
  }

  GetToken(username: HTMLInputElement, password: HTMLInputElement) {
    this.loaderService.display(true);

    const tokenObj = {
      username: username.value,
      password: password.value
    };

    this.auth.GetToken(tokenObj)
      .subscribe((resp: any) => {
        localStorage.setItem('token', resp.token);
        this.router.navigate(['payments']);
      });
    this.loaderService.display(false);
  }

}

auth.interceptor.ts

import { HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import 'rxjs/add/operator/do';

export class AuthInterceptor implements HttpInterceptor {

    intercept(req: HttpRequest<any>, next: HttpHandler) {

      const token = localStorage.getItem('token');
      const newReq = req.clone({
        headers: req.headers.set(
          'Authorization', token
        )
      });

      return next.handle(newReq)
        .do(
          succ => console.log(succ),
          err => console.log('error')
        );
    }
}

CustomException

export class CustomException {
  constructor(public text: string, public code: number, public errObj: any = null) {}
}

global-exception-handler.ts

import { HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import 'rxjs/add/operator/do';

export class AuthInterceptor implements HttpInterceptor {

    intercept(req: HttpRequest<any>, next: HttpHandler) {

      const token = localStorage.getItem('token');
      const newReq = req.clone({
        headers: req.headers.set(
          'Authorization', token
        )
      });

      return next.handle(newReq)
        .do(
          succ => console.log(succ),
          err => console.log('error')
        );
    }
}

payment.components.ts

import { Component, OnInit } from '@angular/core';
import {PaymentService} from '../services/payment.service';
import {Payments} from '../models/payments';
import {Router} from '@angular/router';

@Component({
  selector: 'app-payment',
  templateUrl: './payment.component.html',
  styleUrls: ['./payment.component.css']
})
export class PaymentComponent implements OnInit {


  payment: Payments[];
  public errorMessage ;
  constructor(private pay: PaymentService, private router: Router) { }

  ngOnInit() {
    this.pay.GetPayments()
      .subscribe((resp: any) => {
        this.payment = resp;
        console.log(resp);
    }, error => {
         this.errorMessage = 'Exception occured!';
      });
  }

}

payment.component.html

<div *ngIf="payment; then ifBlock else elseBlock">...</div>
<ng-template #elseBlock>
  <div id="fountainG">
  <div id="fountainG_1" class="fountainG"></div>
  <div id="fountainG_2" class="fountainG"></div>
  <div id="fountainG_3" class="fountainG"></div>
  <div id="fountainG_4" class="fountainG"></div>
  <div id="fountainG_5" class="fountainG"></div>
  <div id="fountainG_6" class="fountainG"></div>
  <div id="fountainG_7" class="fountainG"></div>
  <div id="fountainG_8" class="fountainG"></div>
</div></ng-template>
<p>{{ errorMessage }}</p>
<ng-template #ifBlock>
<div class="container">
  <div class="row">
<table class="table table-striped table-bordered" *ngIf="payment != 0 ">
  <tr class="" *ngFor="let payment of payment">
    <td>{{payment.poutPassport}}</td>
    <td>{{payment.poutAmount}}</td>
    <td>{{payment.poutRrn}}</td>
    <td>{{payment.currency}}</td>
  </tr>
</table>
</div>
</div></ng-template>

1 个答案:

答案 0 :(得分:0)

当我想添加错误路线时,出现以下错误。|

PS:我无法为此添加图片作为评论,因此我添加为答案。

import {ErrorHandler} from '@angular/core'; 
import {Router} from '@angular/router';

export class GlobalExceptionHandle implements ErrorHandler {

  constructor(private router: Router) {}
  handleError(error) {
    console.log(error);
    localStorage.removeItem('token');
    this.router.navigate(['login']);
  }

}

enter image description here