我正在为AngularJS创建一个SOAP请求拦截器
看起来是这样的:
angular.module('myApp')
.factory('SoapInterceptor', ['$q', function ($q) {
var soapRequest = function (url, SOAPAction, requestEnvelope, callback) {
$.soap({
url: url,
appendMethodToURL: false,
SOAPAction: SOAPAction,
enableLogging: false,
data: requestEnvelope,
success: function (SOAPResponse) { callback(SOAPResponse.toJSON()); },
error: function (SOAPResponse) { throw new Error(SOAPResponse); }
});
}
return {
'request': function (config) {
if (config.data && config.data.isSoap) {
var deferred = $q.defer();
soapRequest(config.url, config.data.soapaction, config.data.requestEnvelope, function (data) {
angular.extend(data, config);
deferred.resolve(data);
});
return deferred.promise;
}
return config;
},
'response': function (response) {
// I somehow want this returned response to be my soap response
// which i have got in request but of course it's no use there
return response;
}
}
}]);因此,我可以在数据存储的方法中使用它,如下所示:
var deferred = $q.defer();
$http.post("http://myapi.com/service.asmx",
{
isSoap: true,
requestEnvelope: reqXml,
soapaction: "http://myapi.com/CampaignsGetList"
})
.success(function (data) {
deferred.resolve(data);
});
return deferred.promise;当isSoap为真时,请求正确地将它传递给我的soapRequest,但是如何传递响应,我将返回到响应函数,这样我的使用者就可以愉快地使用这个承诺了。
任何帮助都是非常感谢的。
发布于 2014-10-22 21:05:47
如果我正确理解了这一点,那么您要做的就是在请求内容的数据将$http标记isSoap设置为true时覆盖true服务的行为。看一看您的代码,您似乎实际上希望通过使用拦截器来处理$http调用。
问题是,拦截器不应该那样使用,拦截器应该做的是在http request发生之前和/或之后处理一些事情,但它们不应该自己处理http request。
不过,我觉得你想要的是这样的:
定义自己的"HttpSoap服务“,如下所示:
app.service('HttpSoap', ['$q', function ($q) {
return function (url, SOAPAction, requestEnvelope) {
var deferred = $q.defer();
$.soap({
url: url,
appendMethodToURL: false,
SOAPAction: SOAPAction,
enableLogging: false,
data: requestEnvelope,
success: function (SOAPResponse) { deferred.resolve(SOAPResponse.toJSON()); },
error: function (SOAPResponse) { deferred.reject(SOAPResponse) }
});
return deferred.promise;
}
}]);像这样使用它:
app.controller('myController', function ($scope, HttpSoap) {
// other code here where I assume that you will define
// the reqXml variable
HttpSoap("http://proxy-send.concep.com/service.asmx", "http://new.cl.truelogic.com.au/CampaignsGetList", reqXml)
.then(function (jsonData) {
//things went well
}, function (errorResponse) {
//something bad happened
});
});我还想指出几点:
callback函数中包含的factory参数,因为在角度上使用callbacks是个坏主意,所以使用$q承诺要好得多。https://stackoverflow.com/questions/26515156
复制相似问题