Question

It's been 3months since I've used angular and I'm loving it. Finished an app using it and now I'm on a code refactoring or improving my code for better practice. I have an Api service.js that used $http and I want to migrate it to using $resource :)

I have here a sample of my api code using $http:

Service.js
authenticatePlayer: function(postData) {
        return $http({
          method  : 'POST',
          url     : api + 'auth/player',
          data    : postData,
          headers : {'Content-Type' : 'application/json'}
        });
      },

#Controller.js
Api.authenticatePlayer(postData).then(function (result){
    //success   
}, function(result) {
    //error also this will catch error 400, 401, and 500
});

The above code are working and now here is my first attempt on using $resource:

authenticate: function() {
    return $resource(api + "auth/:usertype",
        {
          typeOfUser : "@usertype" //types can be player, anonymous, admin
        },
        {
          post : { method : "POST" }
        }
    );
}
#Controller
var postData = {
    email    : scope.main.email,
    password : scope.main.password
};

var loginUser = new Api(postData);
loginUser.$post(); //error T__T

That just how far I get, don't know how to pass a data to my api using $resource from my controller. That just one part of my api call, there's still a bunch of it but for now this will do. :D.

Any help is greatly appreciated.

Thanks

Was it helpful?

Solution

You could try this:

API

authenticate: function(){
  return $resource(api+"auth/:usertype",{},post:{method:"POST"});
}

Note: :usertype in URL means that the value of usertype property which you passed into postData will replace the part of URL

Controller

var postData = {email:scope.main.email,password:scope.main.password};

API.authenticate().post({usertype:'player'},postData,function(response){
  console.log(response);
});

Or you could fetch response like this:

var response = API.authenticate().post({usertype:'player'},postData);

Hope this is helpful.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top