import {Inject, Injectable, InjectionToken} from '@angular/core'; import {Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; import {ReplaySubject} from 'rxjs/ReplaySubject'; import {Observable} from 'rxjs/Observable'; import 'rxjs/add/observable/of'; import 'rxjs/add/observable/throw'; import {ErrorObservable} from 'rxjs/Observable/ErrorObservable.js' import {CacheService} from 'ng2-cache'; import { HttpClient } from '../../common/HttpClient'; import { NotFoundError } from '../../models/error/not-found-error'; import { GeneralBackendError } from '../../models/error/general-backend-error'; export let API_URL = new InjectionToken('api_url'); export let IMAGE_URL = new InjectionToken('imageUrl'); @Injectable() export class HelpersService { constructor(@Inject(API_URL) private api_url: string, @Inject(IMAGE_URL) private imageUrl: string, private http: HttpClient, private cacheService: CacheService) { } createRequestOptionsArgs(params?): RequestOptionsArgs { let options = {}; let headers = new Headers(); headers.append('Accept-Language', 'EN'); headers.append('Accept', 'application/json'); options['headers'] = headers; if (params) { let _params = new URLSearchParams(); for (let param_name in params) { _params.set(param_name, params[param_name]); } options['params'] = _params; } return options; } getApiPath(endpoint, segment?: string): Observable { let path = `${this.api_url}${endpoint}`; if (segment) { path += '/' + segment; } return Observable.of(path); } getApiPathForTypicals(endpoint): string { let path = this.api_url + endpoint; return path; } getImageUrl(): string{ return this.imageUrl; } handleHttpError(error: Response | any) { console.error(error); let body; try { body = error.json(); } catch (e) { body = {}; } const code = body.code || error.status; const message = body.message || error.message || error.statusText; const description = body.description; let err; if (error.status == 404) { err = new NotFoundError(message, description, code); } else { err = new GeneralBackendError(message, description, code); } return Observable.throw(err); } composeCacheKey(url, method, options): string { let optionsKey = ''; if (options) { if (options.params instanceof URLSearchParams) { optionsKey += options.params.toString(); } if (options.headers instanceof Headers) { optionsKey += options.headers.toJSON(); } } return JSON.stringify(url) + method + optionsKey; } cachingGet(url: string, options?: RequestOptionsArgs): Observable { let cacheKey = this.composeCacheKey(url, 'get', options); if (!this.cacheService.exists(cacheKey)) { let subject = new ReplaySubject(1); this.http.getWithOptions(url, options, '').subscribe(subject); this.cacheService.set(cacheKey, subject); } // const observable = new Observable(); // (observable).source = this.cacheService.get(cacheKey); // return observable; return this.cacheService.get(cacheKey).asObservable(); } }