2016-07-22 2 views
2

Javascript에서 HTTP 요청을 만들고이 요청의 결과를 얻는 함수를 만들려고합니다. 불행하게도, 나는 절대적으로 .. 타 기능이 결과를 다시 얻는 방법을Angular JS에서 HTTP 요청의 가치를 되 찾으십시오.

여기 모두 내 기능을 찾기를 모르는 (모두 같은 일을 수행해야합니다) :

$scope.getInfo = function() { 
     return $http({ 
      method: 'GET', 
      url: 'https://api.net' 
     }).then(function (response) { 
      return response.data; 
     }); 
    }; 

그리고 다른 하나는 :

$scope.getInfo = function() { 
     var defer = $q.defer(); 
     $http.get('https://api.net').then(function(response) { 
      defer.resolve(response.data); 
     }, function(response) { 
      defer.reject(response); 
     }); 
     return defer.promise; 
    }; 

나는 '요청을 할 수있는 방법에 대해 많은 기사를 찾았지만 그 값 (AN 다른 하나에서 함수의 간단한 전화를 다시 얻을뿐만 아니라 "개체 개체"를 표시하고 I didn 히 한 정확하게 표시하는 해결책을 찾지 못함).

$scope.test = function() { 
     var myValue = $scope.getInfo(); 
     alert(myValue); /* show [Object object] */ 
    }; 

제발 도와 주실 수 있습니까?

답변

1
약속 사용하는 경우는 다음과 같이 진행해야

:

$http({ 
    method: 'GET', 
    url: 'https://api.net' 
}).then(function (response) { 
    $scope.info = response.data 
}); 

현재 코드 반환 약속을 당신이 된 getInfo가 될하려는 경우 그 된 getInfo에 의해 반환 된 결과 개체

로 간주됩니다 이유, 이 같이 할 수있는 기능 :

$scope.getInfo = function() { 
    return $http({ 
     method: 'GET', 
     url: 'https://api.net' 
    }).then(function (response) { 
     return response.data; 
    }); 
}; 

$scope.getInfo().then(function(result) { 
    alert(result); 
}); 
1

$http 서비스를 사용의 일반적인 실수는이 SERV의 반환 값을 할당하는 것입니다 당신이 원하는 것이 아닌 약속 인 변수에 얼음 방법.

$scope.getInfo = function() { 
     return $http({ 
      method: 'GET', 
      url: 'https://api.net' 
     }).then(function (response) { 
      return response.data; 
     }).catch(function(error){ 
      // do something with error 
      throw error; 
     }); 
    }; 

getInfo가 약속하고 원하는 데이터 값으로 해결할 미래에 그 약속을 반환하는 방법이다 :

아래 코드를 고려하십시오.

: 제안 된 방법은 아래와 같이이 방법을 사용하려면 약속 (당신이 console.log(myValue)을 간단하게 할 수 있습니다)입니다

$scope.test = function() { 
     var myValue = $scope.getInfo(); 
     alert(myValue); /* show [Object object] */ 
    }; 

myValue의 가치 : 당신이 컨트롤러에서 다음과 같이 사용하면

$scope.test = function() { 
     $scope.getInfo() 
      .then(function(response){ 
       var myValue = response.data; 
       alert(myValue); /* show [Object object] */ 
      }).catch(function(error) { 
       console.log(error); 
       throw error; 
      }) 

    };