Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get JSON data with AngularJS and add methods on the returning object

Tags:

json

angularjs

I need to get some JSON data from the server with Angular. Let's say the user data. I created a service like that:

app.service('User', function($http) {
  retrun $http({method: 'GET', url:'/current_user'});
});

And in my controller:

app.controller('SomeCtrl', function($scope, User) {
  User.success(function(data) {
    $scope.user = data;
  });
});

That works just fine but what if I want to add some methods to the user? For instance in the view I would like to do {{user.isAdmin()}}. Is it the correct approach? Where can I add those methods?

like image 395
Giorgio Polvara - Gpx Avatar asked Oct 10 '13 14:10

Giorgio Polvara - Gpx


1 Answers

If you wanted your service to always return an object with this method, do something like this:

app.service('User', function($http) {
  return $http({method: 'GET', url:'/current_user'}).
         then(function(response) {
           response.data.isAdmin = function() { return true; };
           return response.data;
         });
});

Now any future code that references this promise and uses .then() will retrieve the new object. Take a look at the promise documentation for more information.

http://docs.angularjs.org/api/ng.$q

Keep in mind by using 'then' on an httpPromise it will be converted to a normal promise. You no longer have the convenience methods 'success' and 'error'.

It may be better practice to create a class for the object you are returning with a constructor function which takes the data object and assigns appropriate properties (or extends the instance). This way you can simply do something like

return new User(val);

And you will get all of the methods you want (with a prototype, etc).

like image 150
Adam Avatar answered Nov 09 '22 19:11

Adam