在 Angular HttpClient 拦截器中使用承诺 [英] Use a promise in Angular HttpClient Interceptor

查看:34
本文介绍了在 Angular HttpClient 拦截器中使用承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在 HttpInterceptor 中使用 promise 吗?例如:

Can I use promise within HttpInterceptor? For example:

export class AuthInterceptor implements HttpInterceptor{
this.someService.someFunction()
    .then((data)=>{
       //do something with data and then
       return next.handle(req);
    });
}

为什么我需要这个?因为在向服务器发出请求之前,我需要获取一个令牌以添加到请求标头中.

why I need this? because I need to get a token to add to request header before making the request to the server.

我的拦截器:

@Injectable()
export class AuthInterceptor implements HttpInterceptor{

    constructor(private authService: AuthService){}

    intercept(req: HttpRequest<any>, next: HttpHandler) : Observable<HttpEvent<any>>{
        console.log('Intercepted!');
        // return next.handle(req);
        this.authService.getToken()
            .then((token)=>{
                console.log(token);
                const reqClone = req.clone({
                    headers: req.headers
                            .set('Authorization', 'Bearer ' + token)
                            .append('Content-Type', 'application/json')
                });
                console.log(reqClone);
                return next.handle(reqClone);
            })
            .catch((err)=>{
                console.log('error in interceptor' + err);
                return null;
            });
    }
}

请求:

this.http.post(this.baseURL + 'hero', data)
                    .subscribe(
                            (res: any) => {
                                console.log('Saved Successfully.');
                                console.log(res);
                            },
                            (err: any) => {
                                console.log('Save Error.' + err);
                            }
                        );

我面临的问题:

->我在承诺解决之前收到此错误.

->I get this error before the promise is resolved.

You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.

Promise resloves 并且我得到了我的令牌但是在错误之后.

Promise resloves and I get my token but after the error.

推荐答案

更新:使用 rxjs@6.x

import { from, Observable } from 'rxjs';
import { switchMap } from 'rxjs/operators';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

    constructor(private authService: AuthService){}

    intercept(request: HttpRequest<any>, next: HttpHandler) : Observable<HttpEvent<any>>{
        return from(this.authService.getToken())
              .pipe(
                switchMap(token => {
                   const headers = request.headers
                            .set('Authorization', 'Bearer ' + token)
                            .append('Content-Type', 'application/json');
                   const requestClone = request.clone({
                     headers 
                    });
                  return next.handle(requestClone);
                })
               );
    }
}

原始答案

是的,您可以将所需的服务注入拦截器的构造方法中,并在intercept的实现中检索该值,创建一个新的更新的http请求并进行处理.

Yes, you could inject the required service into the constructor method of the interceptor, and in the implementation of intercept retrieve the value, create a new updated http request and handle it.

我不擅长承诺,因此您可以尝试以下操作:

I'm not good with promises, so you could try the following:

import { fromPromise } from 'rxjs/observable/fromPromise';

@Injectable()
export class AuthInterceptor implements HttpInterceptor{

    constructor(private authService: AuthService){}

    intercept(req: HttpRequest<any>, next: HttpHandler) : Observable<HttpEvent<any>>{
        return fromPromise(this.authService.getToken())
              .switchMap(token => {
                   const headers = req.headers
                            .set('Authorization', 'Bearer ' + token)
                            .append('Content-Type', 'application/json');
                   const reqClone = req.clone({
                     headers 
                    });
                  return next.handle(reqClone);
             });
    }
}

这篇关于在 Angular HttpClient 拦截器中使用承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆