Skip to content

Instantly share code, notes, and snippets.

@popcorn245
Created November 5, 2015 16:04
Show Gist options
  • Save popcorn245/ce349f9666c648a92800 to your computer and use it in GitHub Desktop.
Save popcorn245/ce349f9666c648a92800 to your computer and use it in GitHub Desktop.
My awesome rest services with promises written in plain old JS.
angular.module('AppName').service('Rest', function($http, $q, $httpParamSerializer){
this.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;
}
this.post(rUrl, rParams) {
if (!rParams) {
rParams = false;
} else {
rParams = this.$httpParamSerializer(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;
}
});
// HOW TO USE
// 1. Inject dependency into controller
// 2. Call Rest.get() or Rest.post()
// a. First param is the URL to send request
// b. Second param is the Data to send in the request
// 3. Call .then to get response
//
// EXAMPLE
// app.controller('HomeController', function(Rest){
// Rest.get('http://google.com').then(function(response){
// console.log(response); // This will be the HTML for Google
// });
// Rest.post('http://google.com', {'param1':'test'}).then(function(response){
// console.log(response);
// });
// });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment