Angular 7 RXJS Observables计时器间隔无限循环立即启动

时间:2018-12-25 15:58:18

标签: angular timer rxjs observable

圣诞快乐!

我正在尝试使这些RXJS可观对象在Angular 7中正常工作,但我不知道出了什么问题。

我想做的是检查每10秒是否有用于身份验证的验证令牌状态。

import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {interval, Observable, of, timer} from 'rxjs';
import {concatMap, delay, flatMap, takeWhile, tap} from 'rxjs/operators';
import {Token} from './Token';
import {User} from './User';
import {TokenFactory} from './factory/tokenfactory';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable({
  providedIn: 'root'
})
export class TokenService {
  private user;
  private token;
  private tokenLoginUrl = 'http://localhost:8080/login_check';
  private refreshTokenUrl = 'http://localhost:8080/token/refresh';

  constructor(private http: HttpClient) { }

  private verifyTokenState(): Observable<any> {
    if (!localStorage.getItem('token')) {
      this.getLoginInfo().subscribe(token => {
        this.token = TokenFactory.createToken(token.token, token.refresh_token, Date.now(), true);
        return of(this.token);
      });
      this.token = {};
      return of(this.token);
    }

    this.token = TokenFactory.getTokenFromLocalStorage();
    const timeElapsedInMinutes = (Date.now() - this.token.date_token) / 1000 / 60;
    console.log(timeElapsedInMinutes);

    if (timeElapsedInMinutes >= 59) {
      this.getRefreshToken(this.token).subscribe(jsonToken => {
        this.token = TokenFactory.createToken(jsonToken.token, jsonToken.refresh_token, Date.now(), true);
        return of(this.token);
      });
    }
    return of(this.token);
  }

  private getLoginInfo(): Observable<any> {
    return this.http.post<Token>(this.tokenLoginUrl, this.user, httpOptions);
  }

  private getRefreshToken(token: Token): Observable<any> {
    return this.http.post<Token>(this.refreshTokenUrl, token, httpOptions);
  }

  public getToken() {
    return timer(0, 10000).pipe(
        flatMap(() => this.verifyTokenState()),
        takeWhile(() => this.token !== undefined && !this.token.isValid)
    );
  }

  public setUser(user: User): void {
    this.user = user;
  }
}

我遇到的问题是,当我从另一个组件内部调用get TokenService.getToken()时(假设用户单击提交按钮后在登录组件中),并且我使用timer(0,10000) getLoginInfo()和 在无限循环中调用getRefreshToken()方法,并且触发了数百个ajax调用。

public getToken() {
    return timer(0, 10000).pipe(
        flatMap(() => this.verifyTokenState()),
        takeWhile(() => this.token !== undefined && !this.token.isValid)
    );
  }

我不明白的是,如果我使用2000而不是0作为第一个参数,则一切正常,但这不是我想要的。

 public getToken() {
        return timer(2000, 10000).pipe(
            flatMap(() => this.verifyTokenState()),
            takeWhile(() => this.token !== undefined && !this.token.isValid)
        );
      }

我想要的是使观察到的两次呼叫之间的间隔为10秒,但我希望它立即开始。我还想获得从verifyTokenSate()方法返回的getToken()返回的可观察令牌。那么到底是怎么了?有更好的方法吗?我想以一种被动的方式做到这一点,而无需取消订阅。

经过进一步调查后,问题似乎在AuthInterceptor中发生。当我从模块提供程序中删除时,一切正常。这是AuthInterceptor:

import {Injectable} from '@angular/core';
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {TokenService} from './token.service';
import {Observable} from 'rxjs';
import {map, mergeMap} from 'rxjs/operators';


@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    private token;
    constructor(private auth: TokenService) { }

    intercept(
        req: HttpRequest<any>,
        next: HttpHandler
    ): Observable<HttpEvent<any>> {
        let request = req.clone();
        this.auth.getToken().subscribe(t => {
            console.log(t);
            if (t.token) {
                console.log('token valid');
                request = req.clone({
                    setHeaders: { Authorization: `Bearer ${t.token}` }
                });
            }
        });

        return next.handle(request);
    }
}

那么AuthInterceptor内部有什么问题?

1 个答案:

答案 0 :(得分:1)

AuthInterceptor可能会截获http登录/刷新URL的请求,进而本身(通过this.auth.getToken())触发这些调用,从而导致循环性。一种可能的解决方案是不拦截(或跳过)这些http请求

intercept(
    req: HttpRequest<any>,
    next: HttpHandler
): Observable<HttpEvent<any>> {
    // whitelisting certain urls that don't need token check
    if (req.url.includes('/login_check')
        || req.url.includes('/token/refresh')) {
        return next.handle(req);
    }

    // remaining code
}