Skip to content

Instantly share code, notes, and snippets.

Created July 13, 2017 19:29
Show Gist options
  • Save anonymous/e0b1ba7f0c5a13383f593c26e9748116 to your computer and use it in GitHub Desktop.
Save anonymous/e0b1ba7f0c5a13383f593c26e9748116 to your computer and use it in GitHub Desktop.
js-45 intercepted-http
import { RequestOptions, Http, XHRBackend } from '@angular/http';
import { InterceptedHttp } from './intercepted-http'
export function interceptedHttpFactory(xhrBackend: XHRBackend, requestOptions: RequestOptions): Http {
return new InterceptedHttp(xhrBackend, requestOptions);
}
import { Injectable } from '@angular/core';
import { ConnectionBackend, RequestOptions, Request, RequestOptionsArgs, Response, Http, Headers, XHRBackend } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { environment } from '../../environments/environment';
// https://scotch.io/@kashyapmukkamala/using-http-interceptor-with-angular2
@Injectable()
export class InterceptedHttp extends Http {
constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
super(backend, defaultOptions);
}
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
return super.request(url, options);
}
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
url = this.updateUrl(url);
return super.get(url, this.getRequestOptionArgs(options));
}
post(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> {
url = this.updateUrl(url);
return super.post(url, body, this.getRequestOptionArgs(options));
}
put(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> {
url = this.updateUrl(url);
return super.put(url, body, this.getRequestOptionArgs(options));
}
delete(url: string, options?: RequestOptionsArgs): Observable<Response> {
url = this.updateUrl(url);
return super.delete(url, this.getRequestOptionArgs(options));
}
private updateUrl(req: string) {
return environment.origin + req;
}
private getRequestOptionArgs(options?: RequestOptionsArgs): RequestOptionsArgs {
if (options == null) {
options = new RequestOptions();
}
if (options.headers == null) {
options.headers = new Headers();
}
options.headers.append('Content-Type', 'application/json');
return options;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment