Skip to content

Instantly share code, notes, and snippets.

@ricmello
Last active May 25, 2018 03:39
Show Gist options
  • Save ricmello/a2d8d1c47250b50ef67a26b63771c80a to your computer and use it in GitHub Desktop.
Save ricmello/a2d8d1c47250b50ef67a26b63771c80a to your computer and use it in GitHub Desktop.
@Injectable()
export class HttpService extends HttpClient {
constructor(private httpHandler: HttpHandler,
private injector: Injector,
@Optional() @Inject(HTTP_DYNAMIC_INTERCEPTORS) private interceptors: HttpInterceptor[] = []) {
super(httpHandler);
if (!this.interceptors) {
// Configure default interceptors that can be disabled here
this.interceptors = [
this.injector.get(LoaderInterceptor),
];
}
}
// Disable loader interceptor
hideLoader(hide: boolean = true): HttpClient {
return hide
? this.removeInterceptor(LoaderInterceptor)
: this;
}
// Override the original method to wire interceptors when triggering the request.
request(method?: any, url?: any, options?: any): any {
const handler = this.interceptors.reduceRight(
(next, interceptor) => new HttpInterceptorHandler(next, interceptor),
this.httpHandler
);
return new HttpClient(handler).request(method, url, options);
}
private removeInterceptor(interceptorType: Function): HttpService {
return new HttpService(
this.httpHandler,
this.injector,
this.interceptors.filter(i => !(i instanceof interceptorType))
);
}
private addInterceptor(interceptor: HttpInterceptor): HttpService {
return new HttpService(
this.httpHandler,
this.injector,
this.interceptors.concat([interceptor])
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment