issue mixing promises with HttpInterceptor observables?

落花浮王杯 提交于 2019-12-23 05:47:08

问题


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:


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);
});


来源:https://stackoverflow.com/questions/45983061/issue-mixing-promises-with-httpinterceptor-observables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!