Skip to content

Instantly share code, notes, and snippets.

@cryptixcoder
Last active November 2, 2017 20:39
Show Gist options
  • Save cryptixcoder/a933df9a43ef64267a7581ce2bad05e7 to your computer and use it in GitHub Desktop.
Save cryptixcoder/a933df9a43ef64267a7581ce2bad05e7 to your computer and use it in GitHub Desktop.
Ionic 2 Rest Provider
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
const BASEURL = "BASEURL";
@Injectable()
export class RestProvider {
constructor(public http: Http) {
console.log('Hello RestProvider Provider');
}
headers(authenticated: boolean = false){
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
if(authenticated){
let token = this.retrieve('token');
headers.append('Authorization', 'Bearer ' + token);
}
return headers;
}
get(url: string, authenticated: boolean = false){
let headers = this.headers(authenticated);
return this.http.get(BASEURL + url, { headers: headers}).map(res => res.json());
}
post(url: string, data: any = null, authenticated: boolean = false){
let headers = this.headers(authenticated);
return this.http.post(BASEURL + url, data, { headers: headers}).map(res => res.json());
}
put(url: string, data: any = null, authenticated: boolean = false){
let headers = this.headers(authenticated);
return this.http.put(BASEURL + url, data, { headers: headers}).map(res => res.json());
}
delete(url: string, authenticated: boolean = false){
let headers = this.headers(authenticated);
return this.http.delete(BASEURL + url, { headers: headers}).map(res => res.json());
}
store(key: string, value: any){
localStorage.setItem(key, value);
}
remove(key){
localStorage.removeItem(key);
}
retrieve(key: string){
return localStorage.getItem(key);
}
destroyStorage(){
localStorage.clear();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment