我在一个组件中使用了多个API,在token过期拦截器运行时,会多次执行。例如,如果我在单个组件中有4个GET API,则在token过期时会运行4次拦截器。
以下是拦截器的代码
my.httpInterceptor.ts
import {
Injectable
} from "@angular/core";
import {
tap
} from "rxjs/operators";
import {
ToastyService,
ToastOptions
} from 'ng2-toasty';
import {
Router
} from "@angular/router";
import {
_throw
} from 'rxjs/observable/throw';
import 'rxjs/add/operator/do';
import 'rxjs/Observable';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor,
HttpResponse,
HttpErrorResponse,
HttpHeaders
} from "@angular/common/http";
import {
Observable
} from "rxjs/Observable";
@Injectable()
export class MyInterceptor implements HttpInterceptor {
constructor(private router: Router, private toastyService: ToastyService, ) {}
//function which will be called for all http calls
intercept(
request: HttpRequest < any > ,
next: HttpHandler
): Observable < HttpEvent < any >> {
//how to update the request Parameters
if (JSON.parse(localStorage.getItem('userDetails'))) {
let authToken = JSON.parse(localStorage.getItem('userDetails'));
if (authToken.currentUserToken != null) {
const authReq = request.clone({
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Bearer' + authToken.currentUserToken
})
});
return next.handle(authReq)
.catch((err) => {
if (err) {
let errorCodes = [404, 500, 422, 412, 424, 409];
if (errorCodes.includes(err.status)) {
let toastOptions: ToastOptions = {
title: "Error",
msg: "Error",
showClose: true,
timeout: 5000,
theme: 'default'
};
toastOptions.msg = err.error.errors.name;
this.toastyService.error(toastOptions);
}
if (err.status === 401) {
this.router.navigate(['/']).then((nav) => {
// debugger;
if (nav) {
if (this.router.url === '/') {
setTimeout(() => {
let toastOptions: ToastOptions = {
title: "Session Expired",
msg: "Please login again to access",
showClose: true,
timeout: 5000,
theme: 'default',
}
// toastOptions.msg = "Session Expired";
this.toastyService.error(toastOptions);
});
}
}
});
}
return _throw(err.message);
}
});
}
} else {
const updatedRequest = request.clone({
headers: new HttpHeaders({
'Content-Type': 'application/json',
})
});
return next.handle(updatedRequest)
}
}
}