angular-基于HTTP响应显示通知

时间:2018-07-24 11:51:13

标签: angular angular-services angular-http angular-http-interceptors

我在后端使用中间件,该中间件处理每个异常并生成如下所示的JSON响应:

{"error":"System.Exception: 'You must be logged in to perform this action.'"}

在我的Angular应用程序中,我想显示一个通知,每次发生异常时都携带异常文本,但是我不确定如何实现。

我想知道是否应该为此使用HttpInterceptor-我也不确定如何正确注册它们-应该在root.module.ts中注册它们才能在整个应用范围内工作,对吗?

有人可以推荐解决方法还是请提供代码示例?

2 个答案:

答案 0 :(得分:2)

绝对使用拦截器。

首先创建服务,然后将其转换为拦截器:

import { Observable } from 'rxjs/Observable';

import {
  HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse
} from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable()
export class ErrorHandlerInterceptor implements HttpInterceptor {

  constructor() { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next
      .catch(err => { /* Display your error here */})
      .handle(req);
  }
}

接下来,您需要在模块中提供它:

  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: ErrorHandlerInterceptor, multi: true },
  ]

答案 1 :(得分:1)

http-intercepter.ts

import { Injectable, Injector } from '@angular/core';
import { Router } from '@angular/router';
import {
    HttpEvent,
    HttpHeaders,
    HttpInterceptor,
    HttpResponse,
    HttpErrorResponse,
    HttpHandler,
    HttpRequest
} from '@angular/common/http';

import { AppService } from './../../core/services/citizen/app-services/app.service';
import { Observable } from 'rxjs/Observable';


@Injectable()
export class TokenInterceptor implements HttpInterceptor {

    constructor(
        private router: Router,
        private appService: AppService) {
    }

    /**
     * 
     * @param req - parameter to handle http request
     * @param next - parameter for http handler
     */
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const started = Date.now();
        /**
         * Handle newly created request with updated header (if given)
         */
        return next.handle(req).do((event: HttpEvent<any>) => {
            /**
             * Sucessfull Http Response Time.
             */
            if (event instanceof HttpResponse) {
                const elapsed = Date.now() - started;
            }

        }, (err: any) => {
            /**
             * redirect to the error_handler route according to error status or error_code
             * or show a modal
             */
            if (err instanceof HttpErrorResponse) {
                switch (err.status) {
                    case 0:
                        console.log("Error type 0")
                        break;
                    case 400:
                        console.log("Error type 400")
                        break;
                    case 401:
                        console.log("Error type 401")
                        break;
                    default:
                        break;
                }
            }
        });
    }
}

在module.ts中:

providers: [
    { provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true },
  ]