angular - 显示基于 HTTP 响应的通知

angular - show notification based on HTTP response

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

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

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

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

有人可以推荐解决方法或提供代码示例吗?

绝对使用拦截器。

首先创建服务并将其转换为拦截器:

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 },
  ]

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 },
  ]