Saurav Tiru Saurav Tiru - 2 months ago 14
AngularJS Question

How to pass specific JSON data from one factory to another factory in Angular JS?

I'm trying to build a simple Weather App using Angular JS.

I've created a -
1)Html Page
2)3 Angular Js components -

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");
})
});


FACTORY 1 - Gets THE IP ADDRESS



//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} });


FACTORY 2- This is where I face problem



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

Answer

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.

Comments