繁体   English   中英

如何以角度发送帖子请求?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM