[英]How to send a post request in angular?
我正在嘗試在我的應用程序中使用帶有 $resource 對象的 POST。
我有這樣的事情。
工廠:
angular.module('toyApp').factory('toys', ['$resource', function ($resource) {
return $resource('/api/v1/toy/:id/condition/:condid',
{ id: '@id',
condid: '@condid' }
);
}]);
控制器:
$scope.addNew = function() {
//how do I pass id and condid below?
toys.save({'name': 'my first toy'});
})
上面的代碼將通過 url 像
/api/v1/toy/condition/
我需要發送請求網址
/api/v1/toy/6666/condition/abd with parame {'name': 'my first toy'}
我該怎么做?
謝謝您的幫助!
API 參考中對此進行了非常清楚的描述:
https://docs.angularjs.org/api/ngResource/service/$resource
$resource(url)
返回的是一個類對象。 如果你想創建一個新實例並保存它,你將在實例上調用$save
方法:
var Toy = $resource('/api/v1/toy/:id/condition/:condid',
{id: '@id', condid: '@condid'});
var toy = new Toy({'id': 123, 'condid': 456, 'name': 'my first toy'});
toy.$save();
但是如果你想調用一個對象創建 API,你必須向你的資源添加一個自定義方法:
var Toy = $resource('/api/v1/toy/:id/condition/:condid',
{id: '@id', condid: '@condid'},
{createToy: {method: 'POST', url: '/create-toy'}});
Toy.createToy({name: 'Slingshot'});
var newToy = new Toys({id: '6666', condid: 'abd'});
newToy.name = 'my first toy';
newToy.$save();
嘗試這個
$scope.addNew = function() {
toys.save({'id': 'foo', 'condid': 'bar'});
})
您將 $http 控制器邏輯外推到服務/工廠是正確的。
創建一個方法來設置您將隨 HTTP POST 請求一起發送的對象。 也可以創建另一種設置 url 的方法。 然后控制器將在保存之前調用這些方法以設置用於 HTTP 調用的 url 和對象。 可以在控制器中指定動態 url(根據需要使用唯一 id 和其他字段)並將其發送到服務。
服務代碼:
var dataObj = [];
var myUrl = "";
//called from controller to pass an object for POST
function setDataObj(_dataObj) {
return dataObj = _dataObj;
};
function setUrl(_url) {
return myUrl = _url;
}
function saveToy() {
//if sending a different type of obj, like string,
//add "headers: { 'Content-Type': <type> }" to http(method, url, header)
$http({ method: 'POST', url: myUrl })
.then(function(data) {
return data;
})
.catch(function(error) {
$log.error("http.post for saveToy() failed!"); //if log is added to service
});
};
控制器代碼:
$scope.id = 574; //or set somewhere else
$scope.condid = 'abd';
$scope.objectYouWantToSend = [{"toyName": "Teddy"}];
// to obtain dynamic url for /api/v1/toy/:id/condition/:condid
$scope.url = '/api/v1/toy/' + $scope.id + '/condition/' + $scope.condid;
$scope.addNewToy = function() {
toyService.setUrl(url); //set the url
toysService.setDataObj($scope.objectYouWantToSend); //set the dataObj
toysService.saveToy(); //call the post method;
};
John Papa 的 AngularJS 風格指南很好地組合在一起,涵蓋了多種格式的場景。 以下是數據服務工廠部分的鏈接: https : //github.com/johnpapa/angular-styleguide#separate-data-calls
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.