Using Http Interceptors in Angular
4/19/23Less than 1 minute
- Create a new interceptor service
HttpInterceptorService
@Injectable()
export class HttpInterceptorService implements HttpInterceptor {
constructor() {}
}- Add the implementation code for the interceptor
@Injectable()
export class HttpInterceptorService implements HttpInterceptor {
constructor() {}
timer;
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
let url = req.url;
const token = localStorage.getItem("token");
if (!token) {
// Throttling to prevent multiple popups at the same time
if (!this.timer) {
this.timer = setTimeout(() => {
clearTimeout(this.timer);
this.message.error("Please login first!");
}, 1000);
}
this.router.navigateByUrl("/");
return;
}
// Set token
req = req.clone({
url,
headers: req.headers.set("Authorization", token),
});
return next.handle(req).pipe(
tap(
(event) => {
if (event instanceof HttpResponse) {
if (event.status != 200) {
console.log(event);
}
// if (event.status >= 500) {
// this.message.error("Server error, please contact the administrator");
// }
}
},
(error) => {
this.message.error("Server error, please contact the administrator");
// this.router.navigateByUrl("/");
}
)
);
}
}Reference Documents
AI Translation | AI 翻译
This article was translated from Chinese to English by AI. If there are any inaccuracies, please refer to the original Chinese version.
本文由 AI 辅助从中文翻译为英文。如遇不准确之处,请以中文原版为准。
