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

时间:2016-09-11 22:31:41

标签: javascript angularjs controller factory

我正在尝试使用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");
        })
    });

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

FACTORY 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的初学者。

此外,控制器和两个工厂都写在不同的 js 文件中。 controller.js factory1.js factory2.js

1 个答案:

答案 0 :(得分:1)

两个函数factory.getIpgetGeoLoc.getGeo都会返回承诺。 承诺,返回值或承诺到下一个。

   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