Skip to content

Instantly share code, notes, and snippets.

@medesko
Created January 12, 2017 13:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save medesko/06b0f9fff23c825e71cd5cb455dcbecc to your computer and use it in GitHub Desktop.
Save medesko/06b0f9fff23c825e71cd5cb455dcbecc to your computer and use it in GitHub Desktop.
Angular 2 - PERFORMANCE
import {
Injectable,
Injector,
} from '@angular/core';
import 'rxjs/add/operator/toPromise';
import {Router} from '@angular/router';
import {
Http,
RequestOptions,
Request,
Headers,
RequestMethod,
Response,
URLSearchParams,
} from '@angular/http';
import {CONFIG} from '../shared/app.config';
@Injectable()
export class ApiService {
private url: string = CONFIG.api.url;
public constructor(private http: Http, private router: Router, private injector: Injector) {
}
public querie(method: string, action: string, params: Object = {}, body: Object = {}, headers: Object = {}, customErrorHandler: Object = {}) {
method = method.substr(0, 1).toUpperCase() + method.substr(1).toLowerCase();
if (action[0] === '/') {
action = action.substr(1);
}
let dataHeaders = new Headers();
for (let key in headers) {
dataHeaders.append(key, headers[key]);
}
let dataSearch = new URLSearchParams();
for (let key in params) {
dataSearch.set(key, params[key]);
}
let requestOptions = new RequestOptions({
method: RequestMethod[method],
url: this.url + action,
headers: dataHeaders,
search: dataSearch,
body: body,
});
return this.http.request(new Request(requestOptions)).toPromise().then((res: Response) => {
return res.json();
}).catch(this.handleError);
}
public get(action: string, params: Object = {}, headers: Object = {}) {
return this.querie('GET', action, params, null, headers);
}
public post(action: string, body: Object = {}) {
return this.querie('POST', action, null, body);
}
public put(action: string, body: Object = {}) {
return this.querie('PUT', action, null, body);
}
public patch(action: string, body: Object = {}) {
return this.querie('PATCH', action, null, body);
}
public delete(action: string, params: Object = {}, headers: Object = {}) {
return this.querie('DELETE', action, params, null, headers);
}
private handleError (error: Response | any) {
// In a real world app, we might use a remote logging infrastructure
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = JSON.parse(err);
} else {
errMsg = error.message ? error.message : error.toString();
}
return Promise.reject(errMsg);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment