1

自从我使用 Angular 已经 3 个月了,我很喜欢它。使用它完成了一个应用程序,现在我正在进行代码重构或改进我的代码以获得更好的实践。我有一个使用 $http 的 Api service.js,我想将它迁移到使用 $resource :)

我在这里有一个使用 $http 的 api 代码示例:

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
});

上面的代码正在运行,现在这是我第一次尝试使用 $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

这就是我能走多远,不知道如何使用来自我的控制器的 $resource 将数据传递给我的 api。这只是我的 api 调用的一部分,还有很多,但现在就可以了。:D。

任何帮助是极大的赞赏。

谢谢

4

1 回答 1

1

你可以试试这个:

API

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

注意: URL 中的 :usertype 表示您传递给 postData 的 usertype 属性的值将替换 URL 的部分

控制器

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

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

或者您可以像这样获取响应:

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

希望这会有所帮助。

于 2013-12-10T06:21:41.567 回答