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 に答える