Angular 4.3 HttpClient拦截器

时间:2017-09-12 15:18:35

标签: angular

请告知为什么路由重定向在响应为401时无效.Console.log显示响应对象和状态为401但路由器未将用户重定向到注销页面。

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

            this.onStart();
            return next.handle(req).do((event: HttpEvent<any>) =>
                (error: any) => {
                    if (error instanceof HttpErrorResponse) {
                        if (error.status == 0 || error.status == 401 || error.status == 404 || error.status == 500 || error.status == 503) {
                            this.storageService.writeToStorage(Constants.STORAGE_KEY_ERROR, error);
                            console.log(error);
                            this.router.navigateByUrl(Constants.ROUTE_ERROR_DYNAMIC + error.status);
                        }
                    }
                    else{
                        return Observable.throw(error);
                    }

                }).finally(() =>{
                    this.onEnd();
                })
        }

4 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情

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

@Injectable()
export class AngularInterceptor implements HttpInterceptor {

  constructor(private router : Router){}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).do(event => {}, err => {
        if(err instanceof HttpErrorResponse){
            console.log("Error Caught By Interceptor");
            //Observable.throw(err);
            this.router.navigate(['a4']);
        }
    });
  }
}

答案 1 :(得分:0)

修改后的代码工作。更改代码以使用catch块。

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

        this.onStart();
        return next.handle(req)
            .catch((error: any) => {
                if (error instanceof HttpErrorResponse) {
                    if (error.status == 0 || error.status == 401 || error.status == 404 || error.status == 500 || error.status == 503) {
                        this.storageService.writeToStorage(Constants.STORAGE_KEY_ERROR, error);
                        this.router.navigateByUrl(Constants.ROUTE_ERROR_DYNAMIC + error.status);
                    }
                }
                return Observable.throw(error);
            })
            .finally(() => {
                this.onEnd();
            })
    }

答案 2 :(得分:0)

在我的案例中添加了return Observable.empty();

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

    this.onStart();
    return next.handle(req)
        .catch((error: any) => {
            if (error instanceof HttpErrorResponse) {
                if (error.status == 0 || error.status == 401 || error.status == 404 || error.status == 500 || error.status == 503) {
                    this.storageService.writeToStorage(Constants.STORAGE_KEY_ERROR, error);
                    this.router.navigateByUrl(Constants.ROUTE_ERROR_DYNAMIC + error.status);
                    return Observable.empty();
                }
            }
            return Observable.throw(error);
        })
        .finally(() => {
            this.onEnd();
        })
}

答案 3 :(得分:0)

我有一段时间了。

就我而言,我要求提供API,但是当我收到401消息时。 我会去登录页面。

但路由器没有工作。

我最终发现现有的请求必须最终确定。

方法是接收错误消息并由请求者处理。

只需拨打&#34;解决(错误)&#34;

因为你应该让他们先走。您在最近的请求呼叫之前路由您的导航网址。

否则,现有请求仍然存在。

流程..

1)请求http呼叫。

2)在拦截器中收到响应401错误。

3)路由你的路径

4)抛出错误

5)错误区域收到错误。

6)解决(错误)或其他消息

在服务中。

getUserInfos(): Promise<any> {
    return new Promise((resolve, reject) => {
        this.http.get('/api/userinfo/list')
          .subscribe((response: any) => {
            this.userInfos = response.data;

            if (this.searchText && this.searchText !== '') {
              this.userInfos = FuseUtils.filterArrayByString(this.userInfos, this.searchText);
            }

            this.userInfos = this.userInfos.map(userInfo => {
              return new UserInfo(userInfo);
            });

            this.onUserInfosChanged.next(this.userInfos);
            resolve(this.userInfos);
          }, **err => {
            resolve(err);
          }**);
      }
    );
  }

.Interceptor

import {
  HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest,
  HttpResponse
} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import {ActivatedRoute, Router} from '@angular/router';
import {Injectable} from '@angular/core';
import 'rxjs/add/observable/throw';
import {FuseConfigService} from './config.service';
import 'rxjs/add/observable/empty';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  constructor(private router: Router, private fuseConfig: FuseConfigService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    console.log('INTERCEPT REQUEST: ', req);
    return next.handle(req)
      .map((event: HttpEvent<any>) => {
        if (event instanceof HttpResponse && ~(event.status / 100) > 3) {
          console.log('INTERCEPT RESPONSE[' + event.status + ']: ', event);
        } else {
          console.log('INTERCEPT RESPONSE[' + event.type + ']: ', event);
          if(event['body'] && event['body'].code == -444) {
            this.router.navigate(['pages/auth/login']);
          }
        }
        return event;
      })
      .catch(
      (err: HttpErrorResponse) => {
        console.log('INTERCEPT ERR[' + err.status + ']: ', err.statusText + ' / ' + err.url);
        if(err.status === 401) {
          this.fuseConfig.setSettings({
            layout: {
              navigation: 'none',
              toolbar   : 'none',
              footer    : 'none'
            }
          });
          **this.router.navigate(['pages/auth/login']);
          return Observable.throw('Unauthorized');**
        }
        return Observable.throw(err);
    });
  }
}