【问题标题】:angular - show notification based on HTTP responseangular - 基于 HTTP 响应显示通知
【发布时间】:2019-01-01 00:44:49
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 你要使用拦截器吗??
  • @UnluckyAj 是的,只要这是最好的方法
  • 是的,这是真的,因为您可以从那里处理所有通知类型。

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


【解决方案1】:

一定要使用拦截器。

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-09
      • 2018-12-18
      • 1970-01-01
      • 2020-10-21
      • 2021-07-08
      • 1970-01-01
      • 1970-01-01
      • 2017-03-05
      相关资源
      最近更新 更多