与HttpInterceptor observables发布混合承诺?

时间:2017-08-31 13:46:35

标签: angular observable angular-promise angular-http-interceptors angular-observable

我正在使用HttpInterceptor以令牌重新发送请求,以防它们返回401。 当我刚刚使用缓存令牌时,这之前运作良好。由于Firebase令牌似乎没有自动刷新(尽管使用forceRefresh),我现在正试图在拦截器类中实时获取新的令牌。问题是现在请求没有被重新发送。

这是我的完整拦截器:

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

如果没有此promise函数来获取新令牌,则使用最后一个“next.handle(changedReq);”重新发送请求。我在这里找不到我做错的事。这是因为我将承诺与可观察者混合在一起吗?

1 个答案:

答案 0 :(得分:0)

通过将承诺转换为Rahul Singh建议的可观察对象,并使用flatMap进行嵌套的可观察返回来解决:

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