发生请求错误后重定向到注销

时间:2018-07-30 12:46:38

标签: angular typescript angular5

我已经将应用程序从angular 2迁移到angular 5,还从不赞成使用的Http迁移到新的HttpClient。

在旧应用程序中,我有以下Http-Client从错误重定向到特定页面。

db.map(query, [], a => a.name)

现在我已经将此重构为HttpInterceptor

import {Router} from "@angular/router";
import {Injectable} from "@angular/core";
import {ConnectionBackend, Http, Request, RequestOptions, RequestOptionsArgs, Response} from "@angular/http";
import {Observable} from "rxjs/Observable";
import "rxjs/add/operator/catch";


@Injectable()
export class HttpService extends Http {

  constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, private router: Router) {
    super(backend, defaultOptions);
  }

  request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
    return super.request(url, options)
      .catch(this.catchErrors());
  }

  private catchErrors() {
    return (res: Response) => {
      if (this.isError(res)) {
        console.log(`Internal server error occured (${res.status} - ${res.statusText})`);
        this.router.navigateByUrl('/error');
      } else if (this.isUnauthorized(res)) {
        console.log(`User is not authenticated  - not logged in or the session expired? (${res.status} - ${res.statusText})`);
        this.router.navigateByUrl('/logout');
      } else if (this.isForbidden(res)) {
        console.log(`User does not have necessary permissions for the resource (${res.status} - ${res.statusText}): ${res.url}`);
        this.router.navigateByUrl('/forbidden');
      }

      return Observable.throw(res);
    };
  }

  private isError(res: Response): boolean {
    return res && res.status === 500;
  }

  private isUnauthorized(res: Response): boolean {
    return res && res.status === 401;
  }

  private isForbidden(res: Response): boolean {
    return res && res.status === 403;
  }

}

但是现在NavigationByUrl无效,甚至可以访问该网站。

有人知道如何解决此问题吗?

2 个答案:

答案 0 :(得分:1)

您可以尝试使用此解决方案

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
             */
            if (err instanceof HttpErrorResponse) {
                switch (err.status) {
                    case 500:
                        console.log(`Internal server error occured (${err.status} - ${err.statusText})`);
                        this.router.navigateByUrl('/error');
                        break;
                    case 400:
                        console.log(`User is not authenticated  - not logged in or the session expired? (${err.status} - ${err.statusText})`);
                        this.router.navigateByUrl('/logout');
                        break;
                    case 403:
                        console.log(`User does not have necessary permissions for the resource (${err.status} - ${err.statusText}): ${err.url}`);
                        this.router.navigateByUrl('/forbidden');
                        break;
                }
            }
        });
}

答案 1 :(得分:1)

您没有收到任何控制台错误消息吗?

我会尝试以下代码:

import {Router} from "@angular/router";
import {Injectable} from "@angular/core";
import {Observable} from "rxjs/Observable";
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse} from "@angular/common/http";


@Injectable()
export class HttpService implements HttpInterceptor {

  constructor(private router: Router) {
  }

  private catchErrors(httpError) {
      if (this.isError(res)) {
        console.log(`Internal server error occured (${res.status} - ${res.statusText})`);
        this.router.navigateByUrl('/error');
      } else if (this.isUnauthorized(res)) {
        console.log(`User is not authenticated  - not logged in or the session expired? (${res.status} - ${res.statusText})`);
        this.router.navigateByUrl('/logout');
      } else if (this.isForbidden(res)) {
        console.log(`User does not have necessary permissions for the resource (${res.status} - ${res.statusText}): ${res.url}`);
        this.router.navigateByUrl('/forbidden');
      }

      return Observable.throw(res);
  }

  private isError(res: HttpResponse<any>): boolean {
    return res && res.status === 500;
  }

  private isUnauthorized(res: HttpResponse<any>): boolean {
    return res && res.status === 401;
  }

  private isForbidden(res: HttpResponse<any>): boolean {
    return res && res.status === 403;
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).catch(httpError => this.catchErrors(httpError));
  }

}

您需要确保将catchErrors函数绑定到HttpService类,并执行Observable.throw以返回失败的Observable

还要检查httpError的类型,在Angular 6+中,我正在使用HttpErrorResponse,但是我不确定较旧版本的类型。