Angularjs issue in relacing Ajax request with promises in service

余生长醉 提交于 2019-12-11 16:20:28

问题


For my Angularjs application in services I have used Ajax call to get the data and is as follows :

var originalRequest = $.ajax({
                    async : false,
                    url : "/dash/dashboard2ajax.do",
                    type : "POST",
                    data : {
                        action : 'getNetSpendOverTime',
                        customerId : selectedAccTd,
                        carriersId : selectedCarriers,
                        fromDate : formattedFromDate,
                        toDate : formattedToDate
                    },
                    dataType : "json",
                    success : function(originalRequest) {
                        var res = originalRequest;
                        data = res.ResultSet.Response;

                    }
                });

Then I just return (data) from my service and in my controller I am able to get data without any problem. But I realized it is a bad practice and trying to use promises. So I have replaced it as follows:

var originalRequest = $http({
            url: "/dash/dashboard2ajax.do",
            method: "POST",
            data: {action : 'getNetSpendOverTime',
                customerId : selectedAccTd,
                carriersId : selectedCarriers,
                fromDate : formattedFromDate,
                toDate : formattedToDate}
        }).success(function(data, status, headers, config) {
           return (data);
        }).error(function(data, status, headers, config) {
            return(status);
        });

But it is not working. None of the parameters are getting even passed to my action class. Is there any mistake in my syntax?

In my action class, I am accessing the parameters as

String action = request.getParameter("action");

But it is coming as null.


回答1:


You're trying to replace jQuery.ajax with AngularJS $http, which has completely different contract. The thing you're calling originalRequest is not in fact any kind of "request object". It's just a Promise (extended with success and error methods). If you want to access the request data outside your success/error handlers, you need to save and pass it separately yourself:

var data = {
    // ...
};
var request = $http({
    data: data,
    // ...
});
return {
    request: request,
    data: data
};

If you need to access it inside the handlers, just get it from the config argument:

$http(...).success(function (data, status, headers, config) {
    var action = config.data.action;
    // ...
});


来源:https://stackoverflow.com/questions/26057909/angularjs-issue-in-relacing-ajax-request-with-promises-in-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!