gpt4 book ai didi

javascript - 如何在 Angular 的 promise 之外获取变量?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:00:17 26 4
gpt4 key购买 nike

<分区>

所以我这里有一个代码:

.factory("Geolocation", ["$cordovaGeolocation",
function ($cordovaGeolocation) {
var posOptions = {
timeout: 10000,
enableHighAccuracy: false
};
var getCurrentPosition = $cordovaGeolocation.getCurrentPosition(posOptions);
return {
lat: function () {
getCurrentPosition.then(function(position) {
return position.coords.latitude; //getting undefined
})
},
long: function() {
getCurrentPosition.then(function(position) {
return position.coords.longitude;
})
}
}

}
])

在我的 Controller 中,我称之为 Geolocation.lat()Geolocation.long()

现在我的问题是我得到的是未定义的而不是纬度和经度。

如果我这样做:

return getCurrentPosition.then(function(position) {
return position.coords.longitude;
})

我得到了另一个多余的 promise ,我只想得到经纬度。

是否有一种简单的方法来访问该 promise 中的变量?

如有任何帮助,我们将不胜感激。

更新(尝试在外部声明一个变量并在 promise 中填充,但我仍然得到一个空值。

.factory("Geolocation", ["$cordovaGeolocation", "$rootScope",
function ($cordovaGeolocation, $rootScope) {
var posOptions = {
timeout: 10000,
enableHighAccuracy: false
};
var getCurrentPosition = $cordovaGeolocation.getCurrentPosition(posOptions);
$rootScope.latitude = null;
$rootScope.longitude = null;
return {
lat: function () {
getCurrentPosition.then(function(position) {
$rootScope.latitude = position.coords.latitude;
})
return $rootScope.latitude;
},
long: function() {
getCurrentPosition.then(function(position) {
return $rootScope.longitude;
})
}
}

}
])

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