Skip to content

Instantly share code, notes, and snippets.

@pearlchen
Created December 19, 2012 23:15
Show Gist options
  • Save pearlchen/4341510 to your computer and use it in GitHub Desktop.
Save pearlchen/4341510 to your computer and use it in GitHub Desktop.
Need to create an AngularJS service that can implement multiple API URL paths, while also post "clean" data? This is my version for a solution. See the bottom of the gist for some more detail.
// YOUR ANGULAR SERVICE
clientApp.factory('Mongo', function($resource) {
// $resource(url[, paramDefaults][, actions]);
return $resource('http://localhost\\:8000/api/:action/:huddleId',
{
action: '@action',
huddleId: '@huddleId'
},
{
create: {
method: 'POST',
params: {action:'createHuddle'}
},
update: {
method: 'POST',
params: {action:'updateHuddle'}
}
});
});
// IN YOUR HTML
// <input type="text" ng-model="huddleLocal.huddleName" />
// <input type="text" ng-model="huddleLocal.huddleExperienceLevel" />
// <button ng-click="create()" />
// <button ng-click="update()" />
// IN YOUR VIEW CONTROLLER
clientApp.controller('CreateCtrl', function($scope, Mongo) {
$scope.huddleLocal = {}; //use this to data bind with the form in the html View
$scope.huddleServer = {}; //use this to store the results coming from the backend
$scope.create = function() {
//Resource.action([parameters], [success], [error]);
$scope.huddleServer = Mongo.create(
{}, //nothing to send so just pass an empty object
function() {
//console.log("create success", $scope.huddleServer);
},
function(err) {
//console.log("create failed", err);
});
}
$scope.update = function() {
// remember that these properties are bound to the HTML form
$scope.huddleLocal.huddleName = "Intro to JavaScript";
$scope.huddleLocal.huddleExperienceLevel = "Beginner";
//Resource.action([parameters], postData, [success], [error]);
$scope.huddleServer = Mongo.update(
{ huddleId: $scope.huddleServer._id }, //Huddle ID used in API path construction pulled from the server object
$scope.huddleLocal, //serialized object data-bound to HTML View w/o ID (b/c sending ID here will create conflict in db)
function() {
//console.log("update success", $scope.huddleServer);
},
function(err) {
//console.log("update failed", err);
});
}
});
/* This is the text from the GIST description since it doesn't seem to support line breaks or any sort of formatting.... */
/*
Need to create an AngularJS service that can implement multiple API URL paths, while also post "clean" data?
As noted in the Angular documentation (http://docs.angularjs.org/api/ngResource.$resource) a parameterized URL template can be made by prefixing your parameters with a colon. e.g. /api/:action/:huddleId
For my current project I have some API calls that look like this:
/api/createHuddle (makes a new document in a Mongo db collection and returns to me the new document)
/api/updateHuddle/123456 (updates the document where the id matches 123456)
/api/doSomethingElse/123456 (some other actions on documents where the id matches 123456)
I feel like there's no direct example of this on the Angular website (especially ones that go beyond 'get', 'set', and 'query') so the first part of the gist shows how my 'Mongo' service looks right now.
I create the service and return an instance of a $resource where:
* 1st parameter = a parameterized URL template using colon prefixes for "action" and "huddleId" (if there's no huddleId, it's just blank)
* 2nd parameter = my parameters that I'm going to use for the URL template. (The @ symbol means that Angular won't pass it along as post data)
* 3rd parameter = an object containing the methods that I will want to call from my Angular Controller (e.g. 'create' and 'update') with some the action parameter already set here (versus trying to construct it in my Controller).
So now that I have my 'Mongo' service, in my Controller I could call them using this format:
Resource.action([parameters], [success], [error]);
// will go to /api/createHuddle
Mongo.create();
// will go to /api/updateHuddle and pass along the object
Mongo.update({huddleId:123456, huddleName:"Intro to JavaScript",huddleExperienceLevel:"Beginner"});
So for 'create', it's pretty straightforward. But for 'update', I'm actually sending along an object that contains the ID. This could potentially create issues since you should rarely try to update a Mongo documentent id.
But there's actually an alternative way of calling 'update' (note the 2nd 'postData' parameter)
Resource.action([parameters], postData, [success], [error]);
// will go to /api/updateHuddle and pass along a "cleaner" version of the object
Mongo.update({huddleId:123456}, {huddleName:"Intro to JavaScript",huddleExperienceLevel:"Beginner"});
Let me know if you have feedback or questions.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment