我在控制器中使用2个服务 第一个服务是获取AjaxResponse,其中提到了获取响应的逻辑 第二个服务调用第一个服务来发出Http请求并获得结果,然后将其返回给控制器
this.getService = secondService.getData(param);
this.httpResponse(param){
var re = $http.get(param);
return re.then(success,fail);
}
function success(data){
return data;
}
function fail(data){
console.log(data);
}
function secondService(firstService){
this.getData = function(param){
return firstService.httpResponse(param);
};
}
this.getService
未定义,所有呼叫都正常进行。
甚至尝试过以下代码:
secondService.getData(param).then(function(data){console.log(data);});
这也没有帮助。
答案 0 :(得分:0)
你应该在这种情况下链接承诺。
首先,您定义您的服务。它应该包含两个不同的功能。例如,我做了GET
和POST
。
angular.module("myApp",[]).factory("SharedServices", function($http) {
return {
getItem: function() {
return $http.get('path/to/api');
},
postItem: function(payload) {
return $http.post('path/to/api', payload);
}
};
});
然后,在控制器中引用该服务。 getItem()
将返回一个承诺,您可以使用.then
在成功回调中调用您的第二个服务。
angular.module("myApp",[]).controller("MainCtrl", function($scope, SharedServices) {
SharedServices.getItem().then(function(response) {
//success, got something
//call the second part
var payload = { myPayload: response.data.someItem };
SharedServices.postItem(payload).then(function(response) {
//success
}, function(response) {
//an error has occurred to the second call--POST
});
}, function(response) {
//an error occurred to the first call--GET
});
});
答案 1 :(得分:0)
使用Callback获取结果。它类似于deferred(promise)