使用拦截器设置授权标头,其中包含可观察到的检索令牌

时间:2019-05-16 14:03:15

标签: angular rxjs angular-http-interceptors

我想使用拦截器将令牌附加到请求标头。使用@ngx-pwa/local-storage存储令牌,该令牌通过Observable返回令牌。

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

我通过以下代码遇到此错误-

import { finalize } from 'rxjs/operators';
import { HttpClient, HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import { catchError, tap, map } from 'rxjs/operators';

import { LocalStorage } from '@ngx-pwa/local-storage';
import { User } from '../models/user';

@Injectable({
    providedIn: 'root'
})
export class httpInterceptorTokenService implements HttpInterceptor {

    constructor ( private localStorage: LocalStorage ) {  }

    private isAuthError(error: any): boolean {
      return error instanceof HttpErrorResponse && error.status == 401;
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      let intialRequest = req.clone();

      return next.handle(req).pipe(
        catchError((error) => {
          if (!this.isAuthError(error)) {
            return Observable.throw(error);
          }

          this.localStorage.getItem<User>('user').subscribe((userData:User) => {
            intialRequest = intialRequest.clone({
              setHeaders: {
                'Authorization': userData.token
              }
            });
            return next.handle(intialRequest).pipe(tap(res => res));
          }); // LOCAL-STORAGE
        })
      ); // RETURN
    } // INTERCEPT
} // EXPORT

是否有解决方案,还是有其他方法可以将令牌附加到每个XHR的标头上?

1 个答案:

答案 0 :(得分:0)

错误的原因是当它是自动化错误时,您没有返回可观察到的结果。 return语句位于预订块内。此外,正如@ jriver27所指出的,您将在管道中添加请求标头以处理错误响应。您需要在进行http调用之前进行处理。

intercept(request: HttpRequest<any>, next: HttpHandler):   Observable<HttpEvent<any>> {
    let result: Observable<HttpEvent<any>> =    next.handle(this.addHeaders(request));
    return result;
}

private addHeaders(request: HttpRequest<any>):   HttpRequest<any> {
    const alteredRequest = request.clone({
      setHeaders: {
        Authorization: `Dummy-Auth   ${this.getDummyToken()}`
            }
    });
    return alteredRequest;
}