[英]Property 'mergeMap' does not exist on type 'Observable<any>'
I'm creating an HttpInterceptor in an Ionic 4 app. 我正在Ionic 4应用程序中创建一个HttpInterceptor。 I would like to read the Bearer Authorization token from local storage .
我想从本地存储中读取Bearer Authorization令牌。
I try to use mergeMap but it always return an error: 我尝试使用mergeMap但它总是返回一个错误:
Property 'mergeMap' does not exist on type 'Observable<any>'
Here is the complete code from token.interceptor.ts 这是来自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);
}));
})
}
}
According to this question , I tried this format: 根据这个问题 ,我尝试了这种格式:
return from(...).pipe(mergeMap(...));
but it doesn't work. 但它不起作用。
What should I try? 我该怎么办?
You are using the syntax of the old RxJS API: 您正在使用旧RxJS API的语法:
import 'rxjs/operators/mergeMap';
myObs$.mergeMap(anotherObs$);
Since the RxJS API changed (version 5.5+), mergeMap
is no longer a method on Observable
but a function and you have to use it in the pipe
operator, like this: 自从RxJS API发生变化(版本5.5+)以来,
mergeMap
不再是Observable
一个方法,而是一个函数,你必须在pipe
运算符中使用它,如下所示:
import { mergeMap } from 'rxjs/operators';
myObs$.pipe(mergeMap(anotherObs$));
Update your imports 更新您的导入
import { map, catchError, mergeMap } from 'rxjs/operators';
Then you can use mergeMap in a pipe. 然后,您可以在管道中使用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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.