Last active
March 20, 2017 10:07
-
-
Save ThomasBurleson/2432692 to your computer and use it in GitHub Desktop.
AngularJS - RESTful CRUD with Services and $http
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// CRUD API for RESTful services with URLs similar 'http://services.mysite.com/classes/Book'. | |
// | |
// e.g. parse.get( | |
// "Book", | |
// 123, | |
// function(response){ console.log(response.toString());} | |
// ); | |
// | |
services.factory('parse', function($rootScope, $http) { | |
var parseUrl = "http://services.mysite.com"; | |
return { | |
//Create a db object on server | |
create: function(className, data, callback) { | |
$http.post( | |
parseUrl+'/classes/'+className, | |
data, | |
{ headers: parseHeaders } | |
) | |
.success(function(response) { | |
forge.logging.log("added object successfully!"); | |
$rootScope.$apply(function() { callback(null, response); }); | |
}) | |
.error(function(response) { | |
forge.logging.log("error adding object!"); | |
$rootScope.$apply(function() { callback("Cannot submit data!"); }); | |
}); | |
}, | |
//Get a db object by id | |
get: function(className, objectId, callback) { | |
$http.get( | |
parseUrl+'/classes/'+className+'/'+objectId, | |
{ headers: parseHeaders } | |
).success(function(response) { | |
$rootScope.$apply(function() { callback(null, response); }); | |
}).error(function(response) { | |
$rootScope.$apply(function() { callback(response.error || "Cannot get object "+className+"/"+objectId+"!"); }); | |
}); | |
}, | |
//Get a list of db objects with query | |
query: function(className, query, callback) { | |
var config = { headers: parseHeaders }; | |
if (query) config.params = { where: query }; | |
$http.get( | |
parseUrl+'/classes/'+className, | |
config | |
).success(function(response) { | |
$rootScope.$apply(function() { callback(null, response); }); | |
}).error(function(response) { | |
$rootScope.$apply(function() { callback(response.error || "Could not query "+className+"!"); }); | |
}); | |
}, | |
//Remove a db object | |
remove: function(className, objectId, callback) { | |
$http['delete']( //['delete'] to get around using delete js keyword | |
parseUrl+'/classes/'+className+'/'+objectId, | |
{ headers: parseHeaders } | |
).success(function(response) { | |
$rootScope.$apply(function() { callback(null, response); }); | |
}).error(function(response) { | |
$rootScope.$apply(function() { callback(response.error || "Cannot delete object "+className+"/"+objectId+"!"); }); | |
}); | |
} | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yeah, it most likely is a typo...