import {Injectable} from '@angular/core'; import {Http, Response, Headers} from '@angular/http'; import {Observable} from 'rxjs'; import 'rxjs/add/operator/map'; @Injectable() export class HttpService { passHeader = new Headers(); constructor(private http: Http) { // this.passHeader.append('Access-Control-Allow-Credentials', 'true'); // this.passHeader.append('Access-Control-Allow-Origin', '*'); // this.passHeader.append('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS'); this.passHeader.append('Content-Type', 'application/json;charset=utf-8'); } getData(conf: any) { return this.requestFn('get', conf); } postData(conf: any) { return this.requestFn('post', conf); } getHeader(newHeader?: any) { if (newHeader) { for (const key of newHeader) { this.passHeader.append(key, newHeader[key]); } } return this.passHeader; } setHttpMath(obj: any) { let temp = obj || {}; temp['_time'] = Math.random().toString(); return temp; } private requestFn(method: string, conf: any): Observable { let url = conf.url; let data: any = conf.data; let search = conf.search || {}; let options: any = { headers: this.getHeader(conf.header || null), search: this.setHttpMath(search) }; // if (!data) { // data = options; // options = null; // } let _m: any; switch (method.toLocaleLowerCase()) { case 'get': return this.http.get(url, options).map((responese: Response) => { const res = responese.json(); if (!res || res.status !== 'success') { throw res; } return res; }); case 'post': if (url.indexOf('?') === -1) { url += '?_time=' + Math.random().toString(); }else{ url += '&_time=' + Math.random().toString(); } return this.http.post(url, data, options).map((responese: Response) => { const res = responese.json(); if (!res || res.status !== 'success') { throw res; } return res; }); } return null; } }