我正在 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(...));
但它不起作用。
我应该尝试什么?
答案 0 :(得分:3)
您使用的是旧版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$));
答案 1 :(得分:0)
更新您的进口商品
import { map, catchError, mergeMap } from 'rxjs/operators';
然后,您可以在管道中使用mergeMap。
const { of } = rxjs; // Using destructuring over import because of snippets
const { mergeMap } = rxjs.operators;
of(4).pipe(
mergeMap(val => of(val * 2))
).subscribe(result => {
console.log(result);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.4.0/rxjs.umd.min.js"></script>