我正在Ionic 4应用程序中创建HttpInterceptor。我想从local storage读取Bearer Authorization令牌。

我尝试使用mergeMap,但它总是返回错误:

Property 'mergeMap' does not exist on type 'Observable<any>'


这是token.interceptor.ts的完整代码

import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, throwError, from  } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
import { Router } from '@angular/router';
import { Storage } from '@ionic/storage';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

    token: any;

    constructor(private router: Router, private storage: Storage) {}

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

        return from(this.storage.get('User')).mergeMap((val) => {
            if (this.token) {
                request = request.clone({
                    setHeaders: {
                        'Authorization': this.token
                    }
                });
            }

            if (!request.headers.has('Content-Type')) {
                request = request.clone({
                    setHeaders: {
                        'content-type': 'application/json'
                    }
                });
            }

            request = request.clone({
                headers: request.headers.set('Accept', 'application/json')
            });

            return next.handle(request).pipe(
                map((event: HttpEvent < any > ) => {
                    if (event instanceof HttpResponse) {
                        console.log('event--->>>', event);
                    }
                    return event;
                }),
                catchError((error: HttpErrorResponse) => {
                    if (error.status === 401) {
                        if (error.error.success === false) {
                            // this.presentToast('Login failed');
                        } else {
                            this.router.navigate(['/']);
                        }
                    }
                    return throwError(error);
                }));
        })

    }

}


根据this question,我尝试了以下格式:

return from(...).pipe(mergeMap(...));


但这不起作用。

我应该怎么做?

最佳答案

您正在使用旧版RxJS API的语法:

import 'rxjs/operators/mergeMap';
myObs$.mergeMap(anotherObs$);


由于RxJS API已更改(5.5版及更高版本),因此mergeMap不再是Observable上的方法,而是一个函数,您必须在pipe运算符中使用它,如下所示:

import { mergeMap } from 'rxjs/operators';
myObs$.pipe(mergeMap(anotherObs$));

08-17 13:54