gpt4 book ai didi

javascript - 如何在 Angular JS 中将特定的 JSON 数据从一个工厂传递到另一个工厂?

转载 作者:行者123 更新时间:2023-12-03 06:08:07 24 4
gpt4 key购买 nike

我正在尝试使用 Angular JS 构建一个简单的天气应用程序。

我创建了一个 -1)HTML页面2)3 Angular Js 组件 -

Controller

angular
.module('weather')
.controller('weatherctrl', function($scope, factory,getGeoLoc){
$scope.ip;
$scope.geoloc;
//city obtainer-

factory.getIP().success(function(data){
$scope.ip = data;

}).error(function(error){
console.log("error");
});

//use the ip obtained on the lo/la api.

getGeoLoc.getGeo().success(function(data){
$scope.geoloc = data

}).error(function(error){
console.log("error");
})
});

工厂 1 - 获取 IP 地址

//This is the factory for data recieving.

angular
.module('weather')
.factory('factory',function($http){function getIP(){
return $http({
method:'GET',
url:'http://ip-api.com/json/'
})
} return {getIP:getIP} });

工厂 2-这是我遇到问题的地方

我必须将 IP 从工厂 1 传递到工厂 2 才能使用经度和纬度

angular
.module('weather')
.factory('getGeoLoc',function($http){

function getGeo(data){
return $http({
method:'GET',
url:'http://api.openweathermap.org/data/2.5/weather?lat='+data.lat+'&lon='+data.lon+'&units=metric&APPID=0bd5e484b08e1c327c6bb917a530ad63',

})


}

return{
getGeo:getGeo
}

});

我尝试过通过/返回

getGeo(getIP)

作为工厂 2 中 getGeo 的函数参数。但它不起作用。

请帮助我,我是 Angular JS 的初学者。

Controller 和两个工厂也写在不同的 js 文件上。 Controller .js工厂1.js工厂2.js

最佳答案

这两个函数,factory.getIpgetGeoLoc.getGeo,都返回 Promise。要链接 promise ,返回值或 promise 到下一个。

   factory.getIp()
.then(function getIpSuccess(response){
$scope.ip = response.data;
//return next promise to chain
return getGeoLoc.getGeo($scope.ip);
}).then(function getGeoSuccess(response) {
$scope.geoloc = response.data;
//return data for chaining
return $scope.geoloc;
}).catch(function onReject(error){
console.log("error ", error.status);
//throw to chain error
throw error;
});

在上面的示例中,如果getIp操作失败,则将跳过getGeo操作。 catch 处理程序将从第一个或第二个 .then 处理程序获取错误。

避免使用.success.error,因为它们会忽略返回(或抛出)值

而是使用.then.catch

关于javascript - 如何在 Angular JS 中将特定的 JSON 数据从一个工厂传递到另一个工厂?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39441276/

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