我有一个这样的angularjs工厂:
'use strict';
angular.module('frontRplApp')
.factory('paymentService', function ($rootScope, $http, config, tools) {
var urlBase = config.baseUrl;
var paymentService = {
response: {},
create: function () {
var args = {};
return $http.post(urlBase + 'api/investor/payment/create', args);
}
});
我打算在这样的控制器中使用它(重要的问题是如果一切顺利或者如果有错误就做一些不同的事情)
$scope.order = function () {
console.log('PaymentCashCtrl.order');
$scope.disabledButtons.submitCashOrder = true;
paymentService.create()
.then(
function (response) {
// do something with response
}, function (error) {
// do something with an error
}));
};
但是我的问题是,我喜欢更新一些paymentService字段,因为$ http.post的响应被解析,然后返回promise,以便控制器中的函数(响应)和函数(错误)回调继续工作 .
我尝试过类似的东西:
return $http.post(urlBase + 'api/investor/payment/create', args)
.then(function(response){
console.log(response);
this.response = response;
return response;
});
但它不起作用,因为从不调用控制器中的函数(错误)处理程序 .
我想在控制器中使用我的处理程序,但在解析$ http.post响应时也会进行一些更新 .
谢谢 .
2 回答
使用
$q
将您的工厂代码更改为:
在工厂中,您需要返回
paymentService
对象的功能 . 另外,不要解决工厂内的承诺 . 在控制器中解决它 .