2016-09-11 5 views
0

저는 Angular JS를 사용하여 간단한 Weather App을 제작하려고합니다. 1) html로 페이지 2) 3 각도 JS 구성 요소 - -Angular JS의 한 공장에서 다른 공장으로 특정 JSON 데이터를 전달하는 방법은 무엇입니까?

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- 이것은 내가 직면 한 문제입니다.

01 23,516,

나는 향해 함수 매개 변수로

getGeo(getIP) 

를 반환/I가 통과 시도했습니다

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 
    } 

}); 

위도와 경도를 사용하는 공장 2 공장 1에서 IP를 통과했습니다 공장에서 getGeo 2.하지만 작동하지 않습니다.

저는 Angular JS의 초보자입니다. 제발 도와주세요.

또한 제어기와 두 개의 공장은 다른 js 파일에 기록됩니다. controller.js 이 factory2.js

답변

1

두 함수, factory.getIpgetGeoLoc.getGeo을 factory1.js, 약속을 반환합니다. 체인 약속, 반환 값 또는 약속합니다. getIp 조작이 실패하면, 상기 예에서

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

getGeo 동작은 생략한다. catch 핸들러는 첫 번째 또는 두 번째 .then 핸들러에서 오류를 가져옵니다.

.success의 사용과 그들이 수익을 무시 (또는 발생) .error때문에이 값.

대신 .then.catch을 사용하십시오.

+0

코드는 원했던대로 작동합니다. 다음 번에 그러한 응답을 올바르게 처리 할 것입니다. –