Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Injectable } from '@angular/core';
- import {Http, Request, RequestOptionsArgs, Response, Headers} from '@angular/http';
- import { Observable } from 'rxjs';
- import { CacheService } from "ionic-cache";
- import { Helper } from '../pages/helper';
- import { AuthService } from './auth.service';
- @Injectable()
- export class HttpService {
- constructor(private helper: Helper,
- private auth: AuthService,
- private http: Http,
- private cache: CacheService) {}
- request(url: string | Request, options?: RequestOptionsArgs): Observable<any> {
- return this.intercept(this.http.request(url, this.getRequestOptionArgs(options)));
- }
- get(url: string, options?: RequestOptionsArgs, cache?:object): Observable<any> {
- if (cache) {
- const groupKey = cache['groupKey'] || 'default';
- const ttl = cache['ttl'] || 60 * 60 * 24 * 7;
- const cacheKey = url;
- const request = this.intercept(this.http.get(url,this.getRequestOptionArgs(options)));
- return this.cache.loadFromObservable(cacheKey, request, groupKey, ttl);
- }
- return this.intercept(this.http.get(url, this.getRequestOptionArgs(options)));
- }
- post(url: string, body: any, options?: RequestOptionsArgs): Observable<any> {
- return this.intercept(this.http.post(url, body, this.getRequestOptionArgs(options)));
- }
- put(url: string, body: any, options?: RequestOptionsArgs): Observable<any> {
- return this.intercept(this.http.put(url, body, this.getRequestOptionArgs(options)));
- }
- delete(url: string, options?: RequestOptionsArgs): Observable<any> {
- return this.intercept(this.http.delete(url, this.getRequestOptionArgs(options)));
- }
- getRequestOptionArgs(options?: RequestOptionsArgs) : RequestOptionsArgs {
- if (!options) {
- options = {
- headers: new Headers()
- }
- }
- let token = this.auth.getToken();
- if (token) {
- options.headers.set("Authorization", "JWT " + token);
- }
- options.headers.set('Content-Type', 'application/json');
- return options;
- }
- intercept(observable: Observable<Response>): Observable<any> {
- return observable
- .map(response => response.text() ? response.json() : response.text())
- .catch((err, source) => {
- const errJson = err.json();
- if (errJson && errJson.message) {
- this.helper.alertWarn(errJson.message);
- } else if (err.status != 401 && err.status != 403 && err.status != 404) {
- this.helper.alertWarn("Um erro inesperado ocorreu.");
- }
- return Observable.throw(err);
- });
- }
- serialize(obj) {
- let str = [];
- for(let p in obj) {
- if (obj.hasOwnProperty(p) && obj[p]) {
- str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
- }
- }
- return str.join("&");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement