Thursday, 20 November 2014

Sending SOAP request using angularjs $HTTP post

In my first project with multi-device hybrid app using cordova+angularjs I did not know how to attach or where to setup the soap request (I'm dealing with an old ASMX webservice) inside the angularjs $http.post syntax. After hours of searching I found out that you can actually include the soap request message inside the "data" parameter of the $http.post command - post(url, data, [config]). See example codes below.


var soapMessage = '<?xml version="1.0" encoding="utf-8"?>\
                            <soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">\
                              <soap12:Header>\
                                <SvcAuthHdr_GetDistrAgreementRecords xmlns="http://tempuri.org/">\
                                  <token>XXXXXX23232SSSS</token>\
                                  <username>9999</username>\
                                  <distance>100</distance>\
                                  <numdaysold>150</numdaysold>\
                                </SvcAuthHdr_GetDistrAgreementRecords>\
                              </soap12:Header>\
                              <soap12:Body>\
                                <GetDistrAgreementRecords xmlns="http://tempuri.org/" />\
                              </soap12:Body>\
                            </soap12:Envelope>';

        var headers = {
            'Content-Type': 'text/xml; charset=utf-8'
        };
        $scope.leadslist = [];

        $http.post(url, soapMessage,
                 { "headers": headers })
                 .success(function (data) {
                     var srchString = '<GetDistrAgreementRecordsResult>0[';
                     var startIdx = data.indexOf(srchString);
                     var endIdx = data.indexOf(']</GetDistrAgreementRecordsResult>');

                     var jsonString = '{"leads":[' + data.substring(startIdx + srchString.length, endIdx) + "]}";

                     var jsonObject = JSON.parse(jsonString);

                     $scope.leadslist = jsonObject.leads;

                 });

4 comments:

  1. Great that you have mentioned clearly about the subject which I have missed at online Angularjs training. Thanks for the clear cut presentation of the information.

    ReplyDelete
    Replies
    1. Thanks for comment. I'm happy to share what I've learned as not all are included in the training course and some of the stuff that you need are not easy to find in the web.

      Delete
  2. This comment has been removed by the author.

    ReplyDelete