issue mixing promises with HttpInterceptor observa

2019-06-12 19:54发布

I am using the HttpInterceptor to resend requests with a token in case they return a 401. This had worked well before, when I was just taking the cached token. Since the Firebase token does not seem to be automatically refreshed (using forceRefresh though), I am now trying to get a fresh token in realtime in the interceptor class. The problem is that now the request is not being re-send.

Here is my full interceptor:

export class CustomHttpInterceptor implements HttpInterceptor {
    constructor(private injector: Injector) {
    }

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

        const formRequest = req.clone({ headers: req.headers.set('Content-Type', 'application/x-www-form-urlencoded') });

        return next.handle(formRequest).map((event: HttpEvent<any>) => {
            if (event instanceof HttpResponse) {
                console.log("GOT RESPONSE WITHOUT ERROR. JUST PASSING THROUGH.");
                return event;
            }
        }).catch(err => {
            console.log("==INTERCEPTOR== CATCH ERROR RESPONSE");
            if (err instanceof HttpErrorResponse) {
                console.log("==INTERCEPTOR== IS HTTP ERROR RESPONSE");
                if (err.status === 401) {
                    console.log("==INTERCEPTOR== IS 401");
                    let postParams = new HttpParams({ fromString: req.body });
                    if (postParams.has('t')) {
                        //401 while we already provided a token, so a real login is required
                        console.log("==INTERCEPTOR== PROVIDED TOKEN, STILL PROBLEM");
                        throw new Error("NOT_AUTH");
                    } else {
                        // most likely session expired, resend token
                        console.log("==INTERCEPTOR== REQUEST WAS WITHOUT TOKEN, RESEND WITH TOKEN");
                        // get AuthProvider here
                        const auth = this.injector.get(AuthProvider);
                        // token will come in a promise
                        return auth.getToken().then(idToken => {
                            console.log("GOT NEW TOKEN, resending request with token " + idToken);
                            //add token to post params
                            let newPostParams = postParams.append('t', idToken); ====> SUCCESFULLY GOT NEW TOKEN
                            //clone request and add new body
                            const changedReq = formRequest.clone({
                                method: 'POST',
                                body: newPostParams.toString()
                            });
                            return next.handle(changedReq);   ====> THIS IS NOT PERFORMED
                        },
                        error => {
                            throw(error);
                        });
                    }
                }
            } else {
                throw(err);
            }
        })
    }
}

Without this promise function to get a new token, the request is being resend using the last "next.handle(changedReq);". I am not finding what I am doing wrong here. Is this caused because I am mixing promises with observables?

1条回答
太酷不给撩
2楼-- · 2019-06-12 20:11

Solved by converting the promise to an observable as suggested by Rahul Singh, and using flatMap in order for the nested observable return:

let promise = auth.getToken();
let observable = Observable.fromPromise(promise);
return observable.first().flatMap(idToken => {
    console.log("GOT NEW TOKEN, resending request with token " + idToken);

    //add token to post params
    let newPostParams = postParams.append('t', idToken);
    //clone request and add new body
    const changedReq = formRequest.clone({
        method: 'POST',
        body: newPostParams.toString()
    });
    return next.handle(changedReq);
});
查看更多
登录 后发表回答