convert ajax call to angularjs http post

2019-05-30 23:10发布

I have an existing WCF (non-RESTful) service that I'm calling using $.ajax. I need to be able to use $http service. I've tried out a few things, but nothing seems be working. The below snippet returns xml successfully, and I'm ok with it as I can't change the service to return json.

var Type = "POST";
var Url = "http://localhost:83928/BookReviewService.svc";
var Data = '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><GetBookReviews xmlns="http://tempuri.org/"><bookReviewsRequest xmlns:a="http://schemas.datacontract.org/2004/07/BookModel" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><a:AmazonCustomerReviewUrl i:nil="true"/><a:AmazonSiteLinkUrl i:nil="true"/><a:Isbn>0393324826</a:Isbn></bookReviewsRequest></GetBookReviews></s:Body></s:Envelope>';
var ContentType = "text/xml; charset=utf-8";
var DataType = "xml";
var ProcessData = true;
CallService();

function CallService() {
    $.ajax({
        type: Type, //GET or POST or PUT or DELETE verb
        url: Url, // Location of the service
        data: Data, //Data sent to server
        contentType: ContentType, // content type sent to server
        dataType: DataType, //Expected data format from server
        processdata: ProcessData, //True or False
        beforeSend: function (xhr) {
            xhr.setRequestHeader("SOAPAction", "http://tempuri.org/IBookReviewService/GetBookReviews");
        },
        success: function (msg) {//On Successfull service call
            ServiceSucceeded(msg);
        },
        error: ServiceFailed// When Service call fails
    });
}

function ServiceFailed(result) {
    console.log(result);
    console.log('Service call failed: ' + result.status + ' ' + result.statusText);
}

function ServiceSucceeded(result) {
    console.log(result);
}

1条回答
一夜七次
2楼-- · 2019-05-30 23:48

Your question reads "convert ajax call to angularjs http post".

To start with you should create a service/factory for all your ajax operations, but that's just a personal preference, would work without that too, read this if you don't want to use service/factory and do directly instead.

angular.module("moduleName").factory('factoryName', ['$http', function ($http) {
    return {
        myFunction: function(data) {
            return $http({
                url: '/user/update',
                method: 'POST',
                data: data
            });
        }
    };
}]);

and in your controller, inject this service and use this function like

factoryName.myFunction();

Ofcourse with a success/error callbacks if needed.

查看更多
登录 后发表回答