I'm trying to build a simple Weather App using Angular JS.
I've created a - 1)Html Page 2)3 Angular Js components -
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");
})
});
//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} });
I've to pass the IP from the factory 1 to factory 2 to use the longitude and latitude
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
}
});
I've tried passing/returning
getGeo(getIP)
as a function parameter towards getGeo in factory 2.But it doesn't work.
Please help me out, im a beginner at Angular JS.
Also the controller and both the factories are written on different js files. controller.js factory1.js factory2.js
Both functions, factory.getIp
and getGeoLoc.getGeo
, return promises. To chain promises, return values or promises to the next.
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;
});
In the above example if the getIp
operation fails, the getGeo
operation will be skipped. The catch handler will get either errors from the first or second .then
handler.
Avoid the use of .success
and .error
because they ignore return (or thrown) values .
Instead use .then
and .catch
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.