gpt4 book ai didi

javascript - 为什么我的 Angular 代码返回未定义?

转载 作者:行者123 更新时间:2023-11-28 18:51:01 25 4
gpt4 key购买 nike

我正在尝试使用 Angular 来使用 Angular 和一些 API 服务来地理定位客户端的地址。我已经让它正确定位了 IP 地址,但由于某种原因我无法执行地理查找。 API 服务运行良好,我的 URL 似乎也很好。

'use strict';

angular.module('Zeus', [])
.controller('ZeusController', function ($scope, $http) {

function fetchIP() {
$http.get("http://ipv4.myexternalip.com/json")
.then(function (response) {
$scope.ip = response.data.ip;
});
return $scope.ip
}

var ip = String(fetchIP());

function geoIP() {
$http.get("https://freegeoip.net/json/" + String(ip))
.then(function (response) {
$scope.country_code = response.data.country_code;
});
return $scope.country_code;
}

var latLon = geoIP();


});

我在 Chrome 控制台中收到以下错误:

Failed to load resource: the server responded with a status of 404 (OK)
https://freegeoip.net/json/undefined

URL 绝对不应该是未定义的,因为使用 Angular 返回 URL 的 IP 会在网络浏览器中返回正确的响应。

最佳答案

这是因为 geoIP() 有回调,您必须处理该回调

像这样

function geoIP() {
return $http.get("https://freegeoip.net/json/" + String(ip))
.then(function(response) {
return response.data.country_code;
});

}
var latLon;
geoIP().then(function(r) {
latLon = r;
})

关于javascript - 为什么我的 Angular 代码返回未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34477975/

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