处理可观察到的未定义值的mergeMap

时间:2018-12-12 09:06:50

标签: javascript angular typescript rxjs

我使用的是角度6,并且有一个类将我的API令牌连接到每个http请求。 getIdToken()成功返回后,一切正常,但是如果返回失败,我的应用程序将停止。

mergeMap失败时如何处理getToken功能?

我对处理mergeMap可观察函数感到困惑。

这是我的课程:

import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse,
    HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/of';
import 'rxjs/add/observable/empty';
import 'rxjs/add/operator/retry';
import 'rxjs/add/operator/mergeMap';
import { of } from 'rxjs';


import { UserService } from '../user/user.service';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

    private token;

    constructor(private userService: UserService) { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return this.userService.getToken().mergeMap(
            (token) => {
                request = request.clone({ headers: request.headers.set('Authorization', token) });
                return next.handle(request);
            }
        );
    }
}

这些是我从userService类获得的getToken函数:

  public async getIdToken() {
    if (this.getCurrentUser() !== null) {
      try {
        const session = await this.getCurrentUserSession();
        return session.getIdToken().getJwtToken();
      } catch (err) {
        return Promise.reject(err);
      }
    } else {
      return Promise.reject('No Current User');
    }
  }

  public getToken(): Observable<any> {
    return Observable.fromPromise(this.getIdToken());
  }

1 个答案:

答案 0 :(得分:0)

尝试像这样在您的mergeMap之前添加渔获物:

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

    return this.userService.getToken()
        .catch(error => // manage your error here)
        .mergeMap(
            (token) => {
                request = request.clone({ headers: request.headers.set('Authorization', token) });
                return next.handle(request);
            }
        );
}