gpt4 book ai didi

javascript - 为 Controller 运行 $http 的服务

转载 作者:行者123 更新时间:2023-11-30 16:47:43 26 4
gpt4 key购买 nike

我有多个 Controller 需要使用我使用 $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 返回一个 promise 。它的实现可以在这里理解: $q

为了使用您的 promise ,您必须执行以下操作:

.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"
});

}
}
})

关于javascript - 为 Controller 运行 $http 的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30982061/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com