Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rewrite jQuery Ajax call in AngularJS

Is there an AngularJS equivalent call to this jQuery ajax POST, with contentType and setRequestHeader?

$.ajax({
    url: "http://localhost/songs",
    type: "POST",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    beforeSend: function (xhr) {
        xhr.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/sharepoint/soap/UpdateListItems");
    },
    success: function(data){
        console.log(data);
    }
});
like image 485
phteven Avatar asked Jul 24 '12 04:07

phteven


Video Answer


1 Answers

You'll probably want to use the $http or $resource service. In the $http doc you can see the section on Setting HTTP Headers to set the SOAPAction and the default content type will be set to json already (though you should be able to override that as well).

This might get you started and I'd be interested to see other answers for a better way because this seems limited.

var module = angular.module('myApp', []);

module.config(function ($httpProvider) {
    $httpProvider.defaults.headers.post['SOAPAction'] = 'http://schemas.microsoft.com/sharepoint/soap/UpdateListItems';
});

function myController($http) {
    var data = { 'value1': 1, 'value2': 2 };

    $http.post('/songs', data).success(function (data) {
        console.log(data);
    });
}

Based on this thread I don't believe you can set the headers differently for each call but it looks like a change might be coming to the $resource service that will allow it.

Update: Must have missed it in the documentation but you can most definitely set different actions per call using $http per this post like this:

var data = { 'value1': 1, 'value2': 2 };

$http.post('/songs', data, {headers: {'SOAPActions': 'http://schemas.microsoft.com/sharepoint/soap/UpdateListItems'}})
    .success(function (data) {
        console.log(data);
    }); 
like image 150
Gloopy Avatar answered Sep 20 '22 00:09

Gloopy