角度3 Http Interceptor Retry请求的ionic 3不起作用

时间:2018-07-11 17:47:23

标签: angular typescript ionic-framework ionic3 angular-http-interceptors

我正在使用带有刷新令牌的令牌身份验证的应用程序。我已经在Web应用程序的angular v1中成功实现了身份验证和刷新令牌。在使用angular v5的ionic 3应用程序中,我还实现了该过程。它通过刷新令牌成功获取了新令牌。但是问题是,它没有再次调用最后一个请求。

这是我的Http拦截器实现。

@Injectable()
export class HttpsRequestInterceptor implements HttpInterceptor {
isRefreshingToken: boolean = false;
tokenSubject: BehaviorSubject<string> = new BehaviorSubject<string>(null);

constructor(
    private injector : Injector
) {

}

addToken(req: HttpRequest<any>, token: string): HttpRequest<any> {
    return req.clone({ setHeaders: { Authorization: 'Bearer ' + token }})
}

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpSentEvent | HttpHeaderResponse | HttpProgressEvent | HttpResponse<any> | HttpUserEvent<any>> {

    const authenticationService = this.injector.get(AuthenticationService);

    let user : AuthenticatedUser = authenticationService.getUser1();

    console.log("token", (user)? user.token : null);

    let dupReq: HttpRequest<any>;

    if (user && req.urlWithParams.indexOf("/token") < 0) {

        dupReq = this.addToken(req, user.token);

    } else {
        dupReq = req;
    }

    return next.handle(dupReq).pipe(
        tap(event => {
            if (event instanceof HttpResponse) {

            console.log(`Request for ${dupReq.urlWithParams} return status text : ${event.statusText} .`);
            }
        }, error => {
            if (error instanceof HttpErrorResponse) {
                switch ((<HttpErrorResponse>error).status) {

                    case 401:
                        return this.handle401Error(dupReq, next);
                }
            } else{
                return Observable.throw(error);
            }
        })
    )
}

handle401Error(req: HttpRequest<any>, next: HttpHandler) {

    if (this.isRefreshingToken == false) {
        this.isRefreshingToken = true;

        this.tokenSubject.next(null);

        const authenticationService = this.injector.get(AuthenticationService);

        return authenticationService.refreshToken().then((result: ResultSet) =>{

            this.isRefreshingToken = false;

            if (result.isSuccess) {

                console.log(result.message, result.model.token);

                let user: AuthenticatedUser  = result.model;
                this.tokenSubject.next(user.token);
                return next.handle(this.addToken(req, user.token));
            } 
            // TODO logout.
        }).catch((error: ResultSet) =>{
            this.isRefreshingToken = false;

            // TODO logout.
        });
    } else {
        return this.tokenSubject
                        .filter(token => token != null)
                        .take(1)
                        .switchMap(token => {
                            return next.handle(this.addToken(req, token));
                        });
    }
}};

任何人都知道拦截器为何不再次重复上一个请求的原因。

谢谢

0 个答案:

没有答案