Javascript 如何在使用Ionic 4中的HttpInterceptor发送请求之前获取承载身份验证令牌
我使用Ionic 4创建一个应用程序。我尝试实现一个HttpInterceptor,将承载授权令牌添加到请求中 问题:在读取令牌之前发送请求 更多详情:Javascript 如何在使用Ionic 4中的HttpInterceptor发送请求之前获取承载身份验证令牌,javascript,angular,typescript,ionic-framework,ionic4,Javascript,Angular,Typescript,Ionic Framework,Ionic4,我使用Ionic 4创建一个应用程序。我尝试实现一个HttpInterceptor,将承载授权令牌添加到请求中 问题:在读取令牌之前发送请求 更多详情: 我尝试从本地存储读取令牌 下面的console.log打印出令牌 怎么了 import {HttpRequest,HttpHandler,HttpEvent,HttpInterceptor,HttpResponse,HttpErrorResponse} from '@angular/common/http'; import { Injectab
import {HttpRequest,HttpHandler,HttpEvent,HttpInterceptor,HttpResponse,HttpErrorResponse} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, throwError } 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) {
this.storage.get('User').then((val) => {
this.token = val;
console.log(val); // Returns the token
});
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log(this.token); // Returns undefined
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);
}));
}
}
import{HttpRequest,HttpHandler,HttpEvent,HttpInterceptor,HttpResponse,HttpErrorResponse}来自'@angular/common/http';
从“@angular/core”导入{Injectable};
从“rxjs”导入{observatable,throwerr};
从“rxjs/operators”导入{map,catchError};
从'@angular/Router'导入{Router};
从'@ionic/Storage'导入{Storage};
@可注射()
导出类TokenInterceptor实现HttpInterceptor{
代币:任何;
构造函数(专用路由器:路由器,专用存储:存储){
this.storage.get('User')。然后((val)=>{
this.token=val;
console.log(val);//返回令牌
});
}
拦截(请求:HttpRequest,下一步:HttpHandler):可观察{
console.log(this.token);//返回未定义的
if(this.token){
request=request.clone({
集合标题:{
“授权”:this.token
}
});
}
如果(!request.headers.has('Content-Type')){
request=request.clone({
集合标题:{
“内容类型”:“应用程序/json”
}
});
}
request=request.clone({
headers:request.headers.set('Accept','application/json')
});
返回next.handle(request.pipe)(
映射((事件:HttpEvent)=>{
if(HttpResponse的事件实例){
console.log('event-->',event);
}
返回事件;
}),
catchError((错误:HttpErrorResponse)=>{
如果(error.status==401){
if(error.error.success===false){
//this.presentToast('Login failed');
}否则{
this.router.navigate(['/']);
}
}
返回投掷器(错误);
}));
}
}
对存储的调用返回一个承诺,因此是异步的。获取intercept函数中的令牌。由于intercept函数需要一个可观察的,因此使用RxJS转换存储调用:
import { from } from 'rxjs';
import { mergeMap } from "rxjs/operators";
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return from(this.storage.get('User')).pipe(
mergeMap((val) => {
// clone and modify the request
request = request.clone({
setHeaders: {
Authorization: val
}
});
[...more stuff you want]
return next.handle(request);
});
)
}
从'rxjs'导入{from};
从“rxjs/operators”导入{mergeMap};
拦截(请求:HttpRequest,下一步:HttpHandler):可观察{
从(this.storage.get('User'))管道返回(
合并映射((val)=>{
//克隆并修改请求
request=request.clone({
集合标题:{
授权:val
}
});
[…更多你想要的东西]
下一步返回。处理(请求);
});
)
}
我没有测试这个函数,但我希望你能理解。可以添加一个if-else语句和令牌作为局部变量,以避免每次调用都从存储器中读取它
token:string;
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if(!this.token)
return from(this.storage.get('User')).pipe(
mergeMap((val) => {
this.token = val
[... modify and return request headers like above]
})
)
else{
[... use this.token for headers ]
}
}
令牌:字符串;
拦截(请求:HttpRequest,下一步:HttpHandler):可观察{
如果(!this.token)
从(this.storage.get('User'))管道返回(
合并映射((val)=>{
this.token=val
[…修改并返回如上所述的请求头]
})
)
否则{
[…对标题使用this.token]
}
}
对存储的调用返回一个承诺,因此是异步的。获取intercept函数中的令牌。由于intercept函数需要一个可观察的,因此使用RxJS转换存储调用:
import { from } from 'rxjs';
import { mergeMap } from "rxjs/operators";
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return from(this.storage.get('User')).pipe(
mergeMap((val) => {
// clone and modify the request
request = request.clone({
setHeaders: {
Authorization: val
}
});
[...more stuff you want]
return next.handle(request);
});
)
}
从'rxjs'导入{from};
从“rxjs/operators”导入{mergeMap};
拦截(请求:HttpRequest,下一步:HttpHandler):可观察{
从(this.storage.get('User'))管道返回(
合并映射((val)=>{
//克隆并修改请求
request=request.clone({
集合标题:{
授权:val
}
});
[…更多你想要的东西]
下一步返回。处理(请求);
});
)
}
我没有测试这个函数,但我希望你能理解。可以添加一个if-else语句和令牌作为局部变量,以避免每次调用都从存储器中读取它
token:string;
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if(!this.token)
return from(this.storage.get('User')).pipe(
mergeMap((val) => {
this.token = val
[... modify and return request headers like above]
})
)
else{
[... use this.token for headers ]
}
}
令牌:字符串;
拦截(请求:HttpRequest,下一步:HttpHandler):可观察{
如果(!this.token)
从(this.storage.get('User'))管道返回(
合并映射((val)=>{
this.token=val
[…修改并返回如上所述的请求头]
})
)
否则{
[…对标题使用this.token]
}
}
我很好奇,如果你在构造函数和拦截函数中都放了一个console.log({code\u LOCATION}'+this.token),它会返回你的令牌吗?@dmoore1181它会返回给构造函数,但在拦截函数中没有定义。我更新了这个问题。我只是建议所有http请求都使用高级http插件。我很好奇,如果你在构造函数和截取函数中都放了一个console.log({CODE_LOCATION}'+this.token),它会返回你的令牌吗?@dmoore1181它会返回给构造函数,但在截取函数中没有定义。我更新了这个问题。我只是建议所有http请求都使用高级http插件。我获取对象(…)(…)。mergeMap不是函数,并且类型上不存在属性mergeMapObservable@LucienDubois很抱歉,这是旧版本的rxjs。我更新了rxjs 6的答案。在这种情况下,您必须使用.pipe(mergeMap(…)。我获取对象(…)(…)。mergeMap不是函数,并且类型上不存在属性mergeMapObservable@LucienDubois很抱歉,这是旧版本的rxjs。我更新了rxjs 6的答案。在这种情况下,必须使用.pipe(mergeMap(…))