Files
mirror-cathay/src/app/app.request.interceptor.ts

46 lines
1.3 KiB
TypeScript

import { Injectable } from '@angular/core';
import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Router } from '@angular/router';
import { AppService } from './app.service';
import { catchError, Observable, throwError } from 'rxjs';
import { environment } from 'src/environments/environment';
import { SathonCathayPayService } from './sathon-cathay-pay.service';
@Injectable()
export class AppRequestInterceptor implements HttpInterceptor {
constructor(
private router: Router,
private appService: AppService,
private sathonSV: SathonCathayPayService
) {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = this.appService.token();
if (token) {
request = request.clone({
setHeaders: { Authorization: `Bearer ${this.generateToken(request.url)}` }
});
}
return next.handle(request).pipe(
catchError((err) => {
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
this.router.navigate(['/auth']);
}
}
return throwError(err);
})
)
}
generateToken(url: string) {
if (url.includes('71dev')) return this.appService.token()
if (url.includes('cathay-pay')) return this.appService.getsathonToken()
}
}