Skip to content

Instantly share code, notes, and snippets.

@RayLuxembourg
Created August 19, 2018 14:42
Show Gist options
  • Save RayLuxembourg/637adafaf7f8a35545a546d4e1c3f17c to your computer and use it in GitHub Desktop.
Save RayLuxembourg/637adafaf7f8a35545a546d4e1c3f17c to your computer and use it in GitHub Desktop.
interceptor
//src/common/services/interceptor.service.ts
import { environment } from '../../../environments/environment';
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HTTP_INTERCEPTORS } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class Interceptor implements HttpInterceptor {
apiRequestHandler(req: HttpRequest<any>): HttpRequest<any> {
const user = JSON.parse(localStorage.getItem('user'));
const pureUrl = req.url.replace("/api", "");
const url = `https://${environment.monitorApi}{pureUrl}`;
let headers = req.headers
.set('custom-header-1', environment.apiClient)
.set('custom-header-2', environment.apiVersion.toString())
.set('custom-header-3', environment.apiType);
if (user) {
headers = headers.set('Authorization', 'Basic ' + btoa(`${user.username}:${user.password}`));
}
return req.clone({
url,
headers
});
}
monitorRequestHandler(req: HttpRequest<any>): HttpRequest<any> {
const pureUrl = req.url.replace("/monitor", "");
const url = `https://${environment.monitorApi}{pureUrl}`;
let headers = req.headers
.set('custom-header-1', 'blalala')
.set('custom-header-2', '72364902 some global variable?')
return req.clone({
url,
headers
});
}
analyticsRequestHandler(req: HttpRequest<any>): HttpRequest<any> {
const pureUrl = req.url.replace("/analytics", "");
const url = `https://${environment.analyticsApi}{pureUrl}`;
let headers = req.headers
.set('secret-key', '892374893')
return req.clone({
url,
headers
});
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.url.startsWith('/api')) {
return next.handle(this.apiRequestHandler(req));
}
if (req.url.startsWith('/monitor')) {
return next.handle(this.monitorRequestHandler(req));
}
if (req.url.startsWith('/analytics')) {
return next.handle(this.analyticsRequestHandler(req));
}
return next.handle(req);
}
}
// use this as a provider in your app module
export const MyInterceptor = {
provide: HTTP_INTERCEPTORS,
useClass: Interceptor,
multi: true
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment