鍍金池/ 問答/HTML5  Unity 3D  HTML/ angular6 攔截器陷入死循環(huán)

angular6 攔截器陷入死循環(huán)

最近項目在使用angular6開發(fā),封裝了一個HttpInterceptor的攔截器,但是一直是報錯的。。

auth.service.ts 里面的代碼

import {Injectable} from '@angular/core';
import {HttpService} from './services/http.service';


@Injectable()
export class AuthService {
  public timestamp: any = '';

  constructor(private http: HttpService) {

  }

  /*
  * 動態(tài)獲取時間戳做驗證
  * */
  getTimestamp() {
    this.http.getData('/common/timestamp').subscribe((respData: any) => {
        if (respData.code === '0000') {
          this.timestamp = respData.data;
        }
      }
    );
  }


  //test用的
  getAuthorizationToken() {
    return 'some-auth-token';
  }
}

interceptor.service.ts

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

import {constant} from '../../providers';
import {AuthService} from '../auth.service';


@Injectable()
export class InterceptorService implements HttpInterceptor {


  constructor(private authService: AuthService) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // const authToken = this.authService.getTimestamp(); //這個代碼放開的話,就陷入死循環(huán)
    const authToken = this.authService.getAuthorizationToken();
    const clonedRequest = req.clone({
      setHeaders: {
        leo: 'test',
        version: constant.VERSIONS,
      },
    });
    console.log(clonedRequest.method);
    return next.handle(clonedRequest).pipe(
      tap(
        event => {
          if (event instanceof HttpResponse) {
            console.log(event);
          }
        },
        error => {
          console.error(error.message);
        }
      )
    );
  }
}

如果我把interceptor.service.ts里面的const authToken = this.authService.getTimestamp();放開,就會陷入循環(huán)。
圖片描述

我想在攔截器的header請求頭里面加個時間戳做驗證,這個時間戳必須是post請求的時候從后臺重新獲取,現(xiàn)在是不知道怎么解決了?有誰知道嗎?謝謝

回答
編輯回答
懶豬

攔截器判斷url /common/timestamp 直接放行

export class InterceptorService implements HttpInterceptor {
  private lastTimestamp;

  constructor(private authService: AuthService) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const authToken;
    if (req.url !== '/common/timestamp'){
        authToken = this.authService.getTimestamp();        
        this.lastTimestamp = authToken;
    } else { // 這里復(fù)用上次時間也可以不要
        authToken = this.lastTimestamp;
    }
    const clonedRequest = req.clone({
      setHeaders: {
        leo: 'test',
        version: constant.VERSIONS,
      },
    });
    console.log(clonedRequest.method);
    return next.handle(clonedRequest).pipe(
      tap(
        event => {
          if (event instanceof HttpResponse) {
            console.log(event);
          }
        },
        error => {
          console.error(error.message);
        }
      )
    );
  }
}
2017年2月10日 04:59