我想要一个从 API 获取信息的服务,但仅在单击 HTML 元素后才获取。
"freegeoip.net/json/" + ip_address
问题是,我的服务和上面的 URL 在点击发生之前被调用。
app.service("ips", function ($http, $q)
{
// Grab json
var deferred = $q.defer();
$http.get("http://www.freegeoip.net/json/" + ip_address).then(function (data)
{
deferred.resolve(data);
});
this.getItems = function ()
{
console.log(deferred.promise);
return deferred.promise;
}
})
有人可以告诉我我可以稍后在点击中定义这个变量 ip_address 吗?
/// Controller 内部
promise.then(function (data)
{
$scope.items = data.data.items;
});
$scope.defineIP= function(item)
{
ip_address = "212.38.168.60"
return ip_address;
}
这里的问题是我不知道如何获取我为 ip_address 定义的值并将其注入(inject)到服务中。
最佳答案
你的代码应该像这样。
app.service("ips", function ($http) {
this.getItems = function (ip_address) {
return $http.get("freegeoip.net/json/" + ip_address)
}
});
在 Controller 中:
$scope.defineIP= function(){
var ip_address = "212.38.168.60"
ips.getItems(ip_address).then(function(response){
console.log(response);
})
}
不要忘记在 Controller 中添加“ips”作为 DI。
当你想获取点击 HTML 元素的信息时,你应该像下面这样调用:
<button ngClick="defineIP()">Click Here</button>
您不需要在服务中注入(inject) $q,因为 $http 返回 Promise 对象,以便您可以直接在 Controller 中使用 .then() 方法
关于javascript - 服务从 Controller 获取 $http API 请求的 URL - Angular.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45371831/