Rich Hopkins
Rich Hopkins

Reputation: 1891

How to send POST with multiple parameters in AngularJS

EDIT: I've updated the web service as shown below. Now I can send a JSON object and get the expected result, using Postman (the web service sends me an email successfully).

I'm brand new to Angular, and the web service I'm hitting is the first I ever wrote, and I need help with sending the POST to the web service.

Here is the signature for the ASP.NET Web API that I'm sending to, and it works properly when I send the POST using Postman (UPDATED):

[HttpPost]
    public bool Post(Email msg)
    {
        return SendEmailMessage(msg);
    }

Here's my controller in AngularJS (UPDATED with vm.msg):

(function () {
angular
    .module('app')
    .controller('About', ['dataService', About]);

function About(dataService) {
    var vm = this;
    //(bunch of stuff removed for brevity)      
    vm.sendMail = function (form) {
        vm.submitted = true;
        vm.mailResult = dataService.sendMail.send(vm.msg);
        if (vm.mailResult) {
            vm.cancel();
        };
    };
    return vm;
}
})();

Here's my service in AngularJS:

(function () {
'use strict';

angular
    .module('app')
    .service('dataService', ['$resource', dataService]);

function dataService($resource) {
    return {
        sendMail: sendMail
    };

    function sendMail(msg) {
        return $resource('/api/email/:data',
            {},
            {
                send: { method: 'POST', params: { data: msg} }
            });
    };
};})();

Here's the POST that I'm sending with Postman, which works:

mywebservice.com/api/email POST with a JSON object sends successfully with Postman to the webservice, and returns the expected result (the webservice sends me an email).

Somehow, I know that my service is screwed up, but I can't figure out what's wrong with it. I've looked at documentation, and examples, but they all have you using a factory, and I am trying to do this using the iife method (again, I'm new at this). Any suggestions are GREATLY appreciated. Thanks! Rich

Upvotes: 0

Views: 1616

Answers (3)

Rich Hopkins
Rich Hopkins

Reputation: 1891

Here's what I ended up doing:

The web service is as edited above, allowing the JSON object to be sent to it. The code in the controller is as follows:

vm.sendMail = function (form) {
        vm.submitted = true;
        vm.msg.message = vm.msg.message.replace(/(\r\n|\n|\r|\n\r)/gm, '<br/>');

        var sendMessage = new emailService();
        sendMessage.$save(vm.msg)
            .then(function () {
                vm.sendSuccess = true;
                vm.sendFailed = false;
                vm.cancel();
            })
            .catch(function() {
                vm.sendSuccess = false;
                vm.sendFailed = true;
                vm.submitted = false;
            });
    };

The code in the service is as follows:

(function() {
'use strict';

angular
    .module('app')
    .service('emailService', ['$resource', emailService]);

function emailService($resource) {
    return $resource('/api/email');
};
})();

Thanks for the help, but I really wanted to learn how to do this with the $resource that I'd started out with.

Upvotes: 0

georgeawg
georgeawg

Reputation: 48968

I recommend that coders first get the API working with the $http service before packaging it into a factory or using a REST api library such as ngResource.

To post to an API that receives the data in URL parameters:

    var config = { params: vm.msg };
    $http.post(url, vm.msg, config)
      .then (function (response) {
        vm.result = "SUCCESS";
        vm.data = response.data;
        console.log(vm.data);
    }).catch(function (error){
        vm.result = "ERROR: "+error.status;
        console.log(error);
    })

The above example posts the data both in the POST body and as URL parameters. The form fills in a message object instead of splitting it into three model variables.

The DEMO

angular.module("app",[])
.controller("ctrl", function($scope, $http){
  var vm = $scope;
  vm.msg = {
    name: "J. Doe",
    email: "[email protected]",
    message: "Hi there"
  };
  var url = "//httpbin.org/post";
  
  vm.submit = function() {
    var config = { params: vm.msg };
    $http.post(url, vm.msg, config)
      .then (function (response) {
        vm.result = "SUCCESS";
        vm.data = response.data;
        console.log(vm.data);
    }).catch(function (error){
        vm.result = "ERROR: "+error.status;
        console.log(error);
    })
  }
})
<script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app="app" ng-controller="ctrl">
    <form ng-submit="submit()">
      Name&nbsp;<input ng-model="msg.name" />
      <br>Email&nbsp;<input ng-model="msg.email" />
      <br>Message
      <br><textarea ng-model="msg.message">
          </textarea>
      <br><button type="submit">Submit</button>
    </form>
    <hr>
    <p>{{result}}</p>
    <p>{{data.url | json}}</p>
    <p>{{data.json | json}}</p>
  </body>

Upvotes: 1

Hadi
Hadi

Reputation: 17289

If you want to send parameters as a query string so you don't need to declare parameter's name.

return $resource('/api/email',{},
        {
            send: { method: 'POST'}
        });

But if you want to send parameter as a rest template so you should declare parameters name.

 return $resource('/api/email/:name/:address/:message',{},
        {
            send: { method: 'POST', params:{name:@name,address:@address,message:@message} }
        });

and call the service like to this in controller

 dataService.sendMail.send({name:vm.name, email:vm.email, message:vm.message});

Upvotes: 0

Related Questions