使用promise从HTTP拦截器返回请求对象

问题描述 投票:0回答:2

我一直在摸不着头几个小时,我希望有人可以帮助我并引导我。所以,我正在开发一个Angular 7应用程序身份验证模块。其中一个要求是开发HTTP拦截器以添加授权(JWT)令牌并处理所有错误消息。

我正在使用NPM包来处理令牌的本地存储。此包使用set和get方法来存储和返回promise而不是令牌的实际值。

现在,我的问题在于我的拦截器功能,如下所示。我试图评论我遇到困难的地方。

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

    // Trying to get the token here but this returns a promise
    // this.token is a service for managing storage and retrieving of tokens
    const token = this.token.getToken();

    // If token is got, set it in the header
    // But when i console log, i see [object promise] other than the token
    if (token) {
        request = request.clone({
            headers: request.headers.set('Authorization', 'Bearer ' + token)
        });
    }

    return next.handle(request).pipe(catchError(err => {
        // Logs out the user if 401 error
        if (err.status === 401) {
            this.token.remove()
                .then(() => {
                    this.auth.changeAuthStatus(false);
                    this.router.navigateByUrl('/login');
                });
        }

        // Returns the error message for the user to see
        // for example in an alert
        const error = err.error.message || err.statusText;
        return throwError(error);
    }));
}

我希望我已经很好地解释了这个问题。我曾尝试在拦截器功能之前使用async,但我得到一个红色讨厌的错误,说TS1055: Type 'typeof Observable' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value.   Types of parameters 'subscribe' and 'executor' are incompatible.

我将非常感谢您解决此问题。

谢谢!

angular angular7 angular-http-interceptors
2个回答
1
投票

要将异步处理合并到您的拦截器中,您希望将您对可观察对象的承诺和switchMap一起推广到您的可观察对象,并返回正确的请求:

import { from as observableFrom } from "rxjs";
import { switchMap } from "rxjs/operators";

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return observableFrom(this.token.getToken()).pipe(
        switchMap(token => {

            // do something with your promise-returned token here

            return next.handle(request).pipe(catchError(err => {
                // Logs out the user if 401 error
                if (err.status === 401) {
                    this.token.remove()
                        .then(() => {
                            this.auth.changeAuthStatus(false);
                            this.router.navigateByUrl('/login');
                        });
                }

                // Returns the error message for the user to see
                // for example in an alert
                const error = err.error.message || err.statusText;
                return throwError(error);
            }));
        })
    );
}

没有直接测试这个代码,所以我为任何错别字道歉,但它应该让你到达你想去的地方。

1)宣传你对from观察的承诺

2)用switchMap链接你的观察者

我注意到你实际上并没有使用你的例子中返回的令牌,你会在switchMap中的函数中做到这一点,它接收到了promise的结果


0
投票

尝试直接从本地存储中获取令牌。为此,当您使用令牌服务方法将令牌存储到本地存储的令牌存储时。

试试以下代码:

token.service.ts

setToken(token) {
    localStorage.setItem('app-token', JSON.stringify(token));
}

getToken() {
    return JSON.parse(localStorage.getItem('app-token'));
}

拦截器代码

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

//This token is retrieved from local storage
const token = this.token.getToken();

// If token is got, set it in the header
// But when i console log, i see [object promise] other than the token
if (token) {
    request = request.clone({
        headers: request.headers.set('Authorization', 'Bearer ' + token)
    });
}

return next.handle(request).pipe(catchError(err => {
    // Logs out the user if 401 error
    if (err.status === 401) {
        this.token.remove()
            .then(() => {
                this.auth.changeAuthStatus(false);
                this.router.navigateByUrl('/login');
            });
    }

    // Returns the error message for the user to see
    // for example in an alert
    const error = err.error.message || err.statusText;
    return throwError(error);
}));
}
© www.soinside.com 2019 - 2024. All rights reserved.