我有多个控制器需要使用使用$ http的自定义服务。我做了这样的事情
.service('getDB', function($http){
return {
fn: function(){
return $http({
url: "http://example.com",
method: "GET"
});
}
}
})
.controller('myCtrl', function($scope, getDB) {
console.log(getDB.fn());
}
在我的getDB.fn()的console.log中,我看到$ promise,如何获取响应数据?
最佳答案
$ http返回一个承诺。它的实现可以在这里理解:
$q
为了兑现诺言,您必须执行以下操作:
.controller('myCtrl', function($scope, getDB) {
getDB.fn(something).then(function(result){
// The result can be accessed here
}, function(error){
//If an error happened, you can handle it here
});
}
这是传递参数的方法:
.service('getDB', function($http){
return {
fn: function(something){
return $http({
url: "http://example.com/" + something,
method: "GET"
});
}
}
})