Skip to content

Instantly share code, notes, and snippets.

@alfredfrancis
Created June 12, 2017 11:13
Show Gist options
  • Select an option

  • Save alfredfrancis/3b9ef54df3b43a321b26f32e2544ea9d to your computer and use it in GitHub Desktop.

Select an option

Save alfredfrancis/3b9ef54df3b43a321b26f32e2544ea9d to your computer and use it in GitHub Desktop.
Common http provider for Angular 4
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { CommonUtilsProvider } from '../../providers/common-utils/common-utils';
import { CommonVariablesProvider } from '../../providers/common-variables/common-variables'
/*
* Common Services Provider
* @author Alfred Francis
* @date 10/06/2017
*/
@Injectable()
export class CommonServiceProvider {
constructor(public http: Http,
private commonUtilsProvider: CommonUtilsProvider,
private commonVariablesProvider: CommonVariablesProvider) {
}
invoke(payload) {
/**
* For calling mypay db router
* @param {json} payload - json payload to be sent
* @return {json}
*/
return new Promise(
(resolve, reject) => {
//retrive loginKey
let userInfo = this.commonUtilsProvider.getUserInfo()
if (userInfo) {
//loginKey is set
payload["aLoginKey"] = userInfo.loginkey;
this.http.post("http://172.30.13.21:8078/mypayroute/route",
payload)
.map(result => result.json())
.subscribe(data => {
resolve(data)
},
errData => {
reject(errData)
}
)
}
else {
//loginKey not set
reject("Invalid loginKey")
}
}
)
}
invokeHTTP(method, context, payload = null) {
/**
* For using common HTTP functions
* @param {string} method - GET,POST,PUT,DELETE
* @param {string} context - context path
* @param {json} payload - json payload to be sent
* @return {json}
*/
let url = this.commonVariablesProvider.apiRouteUrl + context
return new Promise(
(resolve, reject) => {
switch (method) {
case "GET": {
this.http.get(url)
.map(result => result.json())
.subscribe(result => {
resolve(result)
},
err => {
reject(err)
}
)
break;
}
case "POST": {
this.http.post(url, payload)
.map(result => result.json())
.subscribe(result => {
resolve(result)
},
err => {
reject(err)
}
)
break;
}
case "PUT": {
this.http.put(url, payload)
.map(result => result.json())
.subscribe(result => {
resolve(result)
},
err => {
reject(err)
}
)
break;
}
default: {
reject(new Error("Invalid HTTP method."))
break;
}
}
}
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment