简体   繁体   中英

How to send a post request in angular?

I am trying to use POST with $resource object in my app.

I have something like this.

Factory:

angular.module('toyApp').factory('toys', ['$resource', function ($resource) {
    return $resource('/api/v1/toy/:id/condition/:condid',
        { id: '@id',
          condid: '@condid' }

    );
}]);

Controller:

$scope.addNew = function() {
   //how do I pass id and condid below?
   toys.save({'name': 'my first toy'});
})

The above code will pass url like

/api/v1/toy/condition/

I need to send the request url like

/api/v1/toy/6666/condition/abd with parame {'name': 'my first toy'}

How do I do it?

Thanks for the help!

It's very clearly described in the API reference:

https://docs.angularjs.org/api/ngResource/service/$resource

What $resource(url) returns is a class object. If you want to create a new instance and save it, you'll call the $save method on the instance:

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

But if you want to call an object creation API, you'll have to add a custom method to your resource:

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

Try this

$scope.addNew = function() {
    toys.save({'id': 'foo', 'condid': 'bar'});
})

You are correct in extrapolating $http controller logic to a service/factory.

Create a method to set the object that you will send with the HTTP POST request. Another method to set the url may also be created. The controller will then call these methods before saving to set the url and object to be used for the HTTP call. A dynamic url may be specified in the controller (with unique id and other fields as necessary) and sent to the service.

Service code:

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

Controller code:

$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's AngularJS style guide is well put together and covers scenarios in multiple formats. Below is a link to the data-service factory section: https://github.com/johnpapa/angular-styleguide#separate-data-calls

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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