Skip to content

Instantly share code, notes, and snippets.

@popcorn245
Last active September 23, 2015 21:28
Show Gist options
  • Save popcorn245/0f381bb487eafcc95e93 to your computer and use it in GitHub Desktop.
Save popcorn245/0f381bb487eafcc95e93 to your computer and use it in GitHub Desktop.
AngularJS RESTful request service that makes Requests and Promises easier
/// <reference path="../../tsd/angularjs/angular.d.ts"/>
module AppName {
class RestService {
constructor(protected $http: any, protected $q: any, protected $httpParamSerializer) {
// On Load
}
get(rUrl, rParams) {
if (!rParams) {
rParams = false;
} else {
rParams = this.$httpParamSerializer(rParams);
}
var deferred = this.$q.defer();
this.$http.get(rUrl, rParams, {
headers: {
'Content-type': 'application/x-www-form-urlencoded;charset=utf-8'
}
})
.success(function(data, status, headers, config) {
deferred.resolve(data);
})
.error(function(data, status, headers, config) {
console.log('Failed to Get Data from: ' + rUrl);
});
return deferred.promise;
}
post(rUrl, rParams) {
if (!rParams) {
rParams = false;
} else {
rParams = this.$httpParamSerializer(rParams);
}
console.log(rParams);
var deferred = this.$q.defer();
this.$http.post(rUrl, rParams, {
headers: {
'Content-type': 'application/x-www-form-urlencoded;charset=utf-8'
}
})
.success(function(data, status, headers, config) {
deferred.resolve(data);
})
.error(function(data, status, headers, config) {
console.log('Failed to Get Data from: ' + rUrl);
});
return deferred.promise;
}
}
angular.module('AppName').service('Rest', RestService);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment