@angular/common/http#HttpInterceptor TypeScript Examples
The following examples show how to use
@angular/common/http#HttpInterceptor.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: error.interceptor.ts From radiopanel with GNU General Public License v3.0 | 6 votes |
@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
constructor(
private toastr: ToastrService
) {}
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
catchError((error: HttpErrorResponse) => {
this.toastr.error(pathOr('Something went wrong while trying to do that', ['error', 'message'])(error), 'Error');
return throwError(error);
})
);
}
}
Example #2
Source File: api-interceptor.ts From StraxUI with MIT License | 6 votes |
@Injectable({
providedIn: 'root'
})
export class ApiInterceptor implements HttpInterceptor {
constructor() {}
intercept(req: HttpRequest<any>, next: HttpHandler): any {
const finalReq = req.clone({
headers: req.headers.set('Content-Type', 'application/json')
});
return next.handle(finalReq);
}
}
Example #3
Source File: error.interceptor.ts From angular-10-jwt-refresh-tokens with MIT License | 6 votes |
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private authenticationService: AuthenticationService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(catchError(err => {
if ([401, 403].includes(err.status) && this.authenticationService.userValue) {
// auto logout if 401 or 403 response returned from api
this.authenticationService.logout();
}
const error = (err && err.error && err.error.message) || err.statusText;
console.error(err);
return throwError(error);
}))
}
}
Example #4
Source File: app-interceptor.ts From spurtcommerce with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Injectable()
export class AppInterceptor implements HttpInterceptor {
constructor(private spinner: NgxSpinnerService) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.spinner.show();
return next.handle(req).do((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
this.spinner.hide();
}
}, (err: any) => {
if (err instanceof HttpErrorResponse) {
const started = Date.now();
const elapsed = Date.now() - started;
}
});
}
}
Example #5
Source File: jwt.interceptor.ts From angular-10-jwt-refresh-tokens with MIT License | 6 votes |
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(private authenticationService: AuthenticationService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// add auth header with jwt if user is logged in and request is to the api url
const user = this.authenticationService.userValue;
const isLoggedIn = user && user.jwtToken;
const isApiUrl = request.url.startsWith(environment.apiUrl);
if (isLoggedIn && isApiUrl) {
request = request.clone({
setHeaders: { Authorization: `Bearer ${user.jwtToken}` }
});
}
return next.handle(request);
}
}
Example #6
Source File: error.interceptor.ts From angular-10-registration-login-example with MIT License | 6 votes |
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private accountService: AccountService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(catchError(err => {
if ([401, 403].includes(err.status) && this.accountService.userValue) {
// auto logout if 401 or 403 response returned from api
this.accountService.logout();
}
const error = err.error?.message || err.statusText;
console.error(err);
return throwError(error);
}))
}
}
Example #7
Source File: error.interceptor.ts From angular-10-role-based-authorization-example with MIT License | 6 votes |
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private authenticationService: AuthenticationService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(catchError(err => {
if ([401, 403].indexOf(err.status) !== -1) {
// auto logout if 401 Unauthorized or 403 Forbidden response returned from api
this.authenticationService.logout();
}
const error = err.error.message || err.statusText;
return throwError(error);
}))
}
}
Example #8
Source File: universal-relative.interceptor.ts From nestjs-angular-starter with MIT License | 6 votes |
@Injectable()
export class UniversalRelativeInterceptor implements HttpInterceptor {
constructor(@Optional() @Inject(REQUEST) protected request: Request) {}
intercept(
req: HttpRequest<unknown>,
next: HttpHandler
): Observable<HttpEvent<unknown>> {
if (this.request && !isAbsoluteURL(req.url)) {
const protocolHost = `${this.request.protocol}://${this.request.get(
'host'
)}`;
const pathSeparator = !req.url.startsWith('/') ? '/' : '';
const url = protocolHost + pathSeparator + req.url;
const serverRequest = req.clone({ url });
return next.handle(serverRequest);
} else {
return next.handle(req);
}
}
}
Example #9
Source File: jwt.interceptor.ts From angular-10-role-based-authorization-example with MIT License | 6 votes |
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(private authenticationService: AuthenticationService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// add auth header with jwt if user is logged in and request is to api url
const user = this.authenticationService.userValue;
const isLoggedIn = user && user.token;
const isApiUrl = request.url.startsWith(environment.apiUrl);
if (isLoggedIn && isApiUrl) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${user.token}`
}
});
}
return next.handle(request);
}
}
Example #10
Source File: error.interceptor.ts From angular-10-signup-verification-boilerplate with MIT License | 6 votes |
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private accountService: AccountService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(catchError(err => {
if ([401, 403].includes(err.status) && this.accountService.accountValue) {
// auto logout if 401 or 403 response returned from api
this.accountService.logout();
}
const error = (err && err.error && err.error.message) || err.statusText;
console.error(err);
return throwError(error);
}))
}
}
Example #11
Source File: app-http.interceptor.ts From nestjs-angular-starter with MIT License | 6 votes |
/**
* This interceptor handles all of the ongoing requests.
* It adds an authentication token if available in the auth-service.
* All of the ongoing requests are passed to the requests-service to handle and show an error if required.
*/
@Injectable()
export class AppHttpInterceptor implements HttpInterceptor {
constructor(
public authService: AuthService,
private requestsService: RequestsService
) {}
intercept(
request: HttpRequest<unknown>,
next: HttpHandler
): Observable<HttpEvent<unknown>> {
// Add our authentication token if existing
if (this.authService.hasCredentials) {
// Check if this request does already contains a credentials to send, if so, don't append our token
if (!request.withCredentials) {
const cloneOptions = {
setHeaders: {
Authorization: `Bearer ${this.authService.savedToken}`,
},
};
request = request.clone(cloneOptions);
}
}
return this.handleRequest(next.handle(request));
}
handleRequest(
request: Observable<HttpEvent<unknown>>
): Observable<HttpEvent<unknown>> {
return this.requestsService.onRequestStarted(request);
}
}
Example #12
Source File: jwt.interceptor.ts From angular-10-signup-verification-boilerplate with MIT License | 6 votes |
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(private accountService: AccountService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// add auth header with jwt if account is logged in and request is to the api url
const account = this.accountService.accountValue;
const isLoggedIn = account && account.jwtToken;
const isApiUrl = request.url.startsWith(environment.apiUrl);
if (isLoggedIn && isApiUrl) {
request = request.clone({
setHeaders: { Authorization: `Bearer ${account.jwtToken}` }
});
}
return next.handle(request);
}
}
Example #13
Source File: error.interceptor.ts From angular-11-crud-example with MIT License | 6 votes |
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private alertService: AlertService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(catchError(err => {
const error = err.error?.message || err.statusText;
this.alertService.error(error);
console.error(err);
return throwError(error);
}))
}
}
Example #14
Source File: api.service.ts From storm with MIT License | 6 votes |
export class ApiInterceptor implements HttpInterceptor {
constructor() {
}
private catchError(err: HttpErrorResponse, caught: Observable<HttpEvent<any>>): ObservableInput<any> {
return throwError(new ApiException(err.status, err.error.Error));
}
public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
catchError(this.catchError)
);
}
}
Example #15
Source File: token.interceptor.ts From radiopanel with GNU General Public License v3.0 | 6 votes |
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(
private router: Router,
) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request)
.pipe(
tap(
() => { },
(err: any) => {
if (err instanceof HttpErrorResponse) {
if (err.status !== 401) {
return;
}
setCookie('loggedIn', 'false', 0);
this.router.navigate(['auth', 'login']);
}
}
)
);
}
}
Example #16
Source File: jwt.interceptor.ts From angular-10-jwt-authentication-example with MIT License | 6 votes |
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(private authenticationService: AuthenticationService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// add auth header with jwt if user is logged in and request is to the api url
const currentUser = this.authenticationService.currentUserValue;
const isLoggedIn = currentUser && currentUser.token;
const isApiUrl = request.url.startsWith(environment.apiUrl);
if (isLoggedIn && isApiUrl) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${currentUser.token}`
}
});
}
return next.handle(request);
}
}
Example #17
Source File: http-error.interceptor.ts From enterprise-ng-2020-workshop with MIT License | 6 votes |
/** Passes HttpErrorResponse to application-wide error handler */
@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
constructor(private injector: Injector) {}
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
tap({
error: (err: any) => {
if (err instanceof HttpErrorResponse) {
const appErrorHandler = this.injector.get(ErrorHandler);
appErrorHandler.handleError(err);
}
}
})
);
}
}
Example #18
Source File: admin-interceptor.ts From mysql_node_angular with MIT License | 6 votes |
@Injectable()
export class AdminInterceptor implements HttpInterceptor {
constructor(private authSvc: AuthService) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<any> {
if (req.url.includes('users')) {
const userValue = this.authSvc.userValue;
const authReq = req.clone({
setHeaders: {
auth: userValue.token,
},
});
return next.handle(authReq);
}
return next.handle(req);
}
}
Example #19
Source File: auth.interceptor.ts From dating-client with MIT License | 6 votes |
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private store: Store<RootState>) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return this.store.select(selectAuthToken).pipe(
first(),
switchMap(token => {
const authRequest = !!token
? req.clone({ setHeaders: { Authorization: `Bearer ${ token }` } })
: req;
return next.handle(authRequest);
})
);
}
}
Example #20
Source File: http-req.interceptor.ts From open-genes-frontend with Mozilla Public License 2.0 | 6 votes |
@Injectable()
export class HttpReqInterceptor implements HttpInterceptor {
constructor() {}
intercept(req: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
let headers = new HttpHeaders();
headers = headers
.append('Accept', 'application/json')
.append('Content-Type', 'application/json');
if (req.url.includes('/api/') && !req.url.includes('https')) {
const request = req.clone({
headers,
url: environment.apiUrl + req.url,
});
return next.handle(request);
}
return next.handle(req);
}
}
Example #21
Source File: cache.interceptor.ts From onchat-web with Apache License 2.0 | 6 votes |
@Injectable()
export class CacheInterceptor implements HttpInterceptor {
constructor(private cacheService: CacheService) { }
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
// 判断当前请求是否可缓存
if (!isCachable(request)) {
return next.handle(request);
}
// 缓存命中则直接返回
const response = this.cacheService.get(request);
if (response) {
return of(response);
}
// 发送请求,成功后缓存
return next.handle(request).pipe(
tap(event => {
event instanceof HttpResponse && this.cacheService.put(request, event);
})
);
}
}
Example #22
Source File: i18n.interceptor.ts From geonetwork-ui with GNU General Public License v2.0 | 6 votes |
@Injectable()
export class I18nInterceptor implements HttpInterceptor {
constructor(private translate: TranslateService) {}
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
request = request.clone({
setHeaders: {
'Accept-Language': this.translate.currentLang || DEFAULT_LANG,
},
})
return next.handle(request)
}
}
Example #23
Source File: http-error.interceptor.ts From assetMG with Apache License 2.0 | 6 votes |
@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
constructor(
public dialog: MatDialog,
) {}
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
catchError((error: HttpErrorResponse) => {
if (error.error instanceof ErrorEvent) {
// client-side error
let errorMessage = `Client Side Error: ${error.error.message}`;
return throwError(errorMessage);
}
if (error.status === 403) {
this.openErrorDialog(error.error);
}
// server-side error
return throwError(error);
})
);
}
openErrorDialog(errorMessage) {
const dialogRef = this.dialog.open(ErrorDialogComponent, {
width: '700px',
disableClose: true,
autoFocus: false,
data: { errorMessage: errorMessage },
});
}
}
Example #24
Source File: http-interceptor.service.ts From ng-ant-admin with MIT License | 6 votes |
@Injectable()
export class HttpInterceptorService implements HttpInterceptor {
constructor(private windowServe: WindowService, public message: NzMessageService) {
}
intercept(req: HttpRequest<NzSafeAny>, next: HttpHandler): Observable<HttpEvent<NzSafeAny>> {
const token = this.windowServe.getSessionStorage(TokenKey);
let httpConfig: CustomHttpConfig = {};
if (!!token) {
httpConfig = {headers: req.headers.set(TokenKey, token)};
}
const copyReq = req.clone(httpConfig);
return next.handle(copyReq).pipe(filter(e => e.type !== 0), catchError(error => this.handleError(error)));
}
private handleError(error: HttpErrorResponse): Observable<never> {
const status = error.status;
let errMsg = '';
if (status === 0) {
errMsg = '网络出现未知的错误,请检查您的网络。';
}
if (status >= 300 && status < 400) {
errMsg = '请求被服务器重定向,状态码为' + status;
}
if (status >= 400 && status < 500) {
errMsg = '客户端出错,可能是发送的数据有误,状态码为' + status;
}
if (status >= 500) {
errMsg = '服务器发生错误,状态码为' + status;
}
return throwError({
code: status,
message: errMsg
});
}
}
Example #25
Source File: base.interceptor.ts From onchat-web with Apache License 2.0 | 6 votes |
@Injectable()
export class BaseInterceptor implements HttpInterceptor {
constructor(private overlay: Overlay) { }
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
return next.handle(request).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status !== 401) {
if (error.error.code === ResultCode.AuthExpires) {
this.overlay.toast('授权令牌过期,请重新登录');
} else {
this.overlay.toast('操作失败,原因:' + (error.error.msg || error.error.message || error.statusText));
}
}
return throwError(() => error);
})
);
}
}
Example #26
Source File: header.interceptor.ts From muino-time-management with GNU General Public License v3.0 | 6 votes |
export class AuthHeaderInterceptor implements HttpInterceptor {
intercept(req : HttpRequest <any>, next : HttpHandler) : Observable <HttpEvent<any>> {
// Clone the request to add the new header
const token = new TokenStorage();
const tokenVal = token.getToken();
const clonedRequest = req.clone({
headers: req
.headers
.set('Authorization', tokenVal ? `Bearer ${ tokenVal}` : '')
});
// Pass the cloned request instead of the original request to the next handle
return next.handle(clonedRequest);
}
}
Example #27
Source File: token-verification.interceptor.ts From litefy with MIT License | 6 votes |
@Injectable({
providedIn: 'root'
})
export class TokenVerificationInterceptorService implements HttpInterceptor {
constructor(private authService: AuthService, private router: Router) { }
lastUrl = '/';
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 401) {
this.Sair();
}
return throwError(error);
}));
}
Sair() {
this.authService.logout();
this.router.navigate(['login']);
}
}
Example #28
Source File: jwt.interceptor.ts From nuxx with GNU Affero General Public License v3.0 | 6 votes |
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(private authenticationService: AuthenticationService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// add auth header with jwt if user is logged in and request is to the api url
const currentUser = this.authenticationService.currentUserValue;
const isLoggedIn = currentUser && currentUser.token;
const isApiUrl = request.url.startsWith(environment.apiUrl);
if (isLoggedIn && isApiUrl && (!request.url.includes('social/github/login') || request.url === `${environment.apiUrl}/recipe/`)) {
request = request.clone({
setHeaders: {
Authorization: `JWT ${currentUser.token}`
}
});
}
return next.handle(request);
}
}
Example #29
Source File: auth.interceptor.ts From svvs with MIT License | 6 votes |
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private authStorage: IAuthStorage) {
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const accessToken = this.authStorage.getAccessToken()
if (accessToken) {
req = req.clone({
headers: req.headers.set('Authorization', `Bearer ${accessToken}`),
})
}
return next.handle(req)
}
}