如何使用angularjs服务将POST变量发送到REST API?
现在我有这个:
angularjsServices.factory('LoginService', [ '$resource',
function($resource){
return function(user, pass){
return $resource(baseURL + "/login", {}, {
logIn: {method:'POST', params:{username: user, password: pass}, isArray:false}
});
}
}]);
这样变量就会在url中发送。 (我正在使用this tutorial的部分,但它使用jQuery而不是angularJS)
答案 0 :(得分:4)
首先,不要混淆您的资源和服务。
仅声明资源,如下所示:
resourceModule.factory('rsrUser', [ '$resource',
function($resource){
return $resource(baseURL + "/login", {}, {
// removed params property, that set pre-bound parameters for this action
logIn: {method:'POST', isArray:false}
});
}
]);
然后您可以在服务或控制器中使用此资源rsrUser:
controllerModule.controller('ctrlMain', [ '$scope', 'rsrUser',
function($scope, rsrUser){
// create resource instance and attach properties (which would become a POST body)
$scope.user = new rsrUser
$scope.user.username = 'savior'
$scope.user.password = '123'
// call resource action
$scope.user.$logIn(function(){
//success callback
}, function() {
//error callback
})
}
]);
答案 1 :(得分:1)
我建议您使用restangular https://github.com/mgonto/restangular
AngularJS服务正确处理Rest API Restful资源 容易
发布你可以做类似的事情
var myBuilding = {
name: "Gonto's Building",
place: "Argentina"
};
// POST /accounts/123/buildings with MyBuilding information
firstAccount.post("Buildings", myBuilding).then(function() {
console.log("Object saved OK");
}, function() {
console.log("There was an error saving");
});