2016-08-02 36 views
3

我想設置一個變量作爲角度從http請求返回的數據對象,但變量從不設置爲即使它在$scope,除非它嵌套在成功功能。例如,如果我這樣做的控制器:作爲對象的角度設置變量通過http

$scope.hello = []; 
     var getAppointmentsurl = './dbscripts/getAppointments.php'; 

      $http({method: 'GET', url: getAppointmentsurl}).success(function(data) { 

       $scope.hello = data; 
      }); 

      console.log($scope.hello); 

} 

Hello是空白的,所以,我把它架在這樣的services.js:

this.getCalendarData=function(){ 
     var hello = []; 
      var getAppointmentsurl = './dbscripts/getAppointments.php'; 

       $http({method: 'GET', url: getAppointmentsurl}).success(function(data) { 

        hello = data; 
       }); 

       return hello; 

    } 

但仍你好是空白。我錯過了明顯的東西嗎?

編輯 - enter image description here

+0

儘量把執行console.log或函數內部的回報,你會看到你的結果 – Vanojx1

+0

所有的數據是「數據',即通過罰款 –

+0

檢查[這](http://stackoverflow.com/questions/12505760/processing-http-response-in-service)。 $ http是異步的,你應該使用不同的方法來得到它的結果。 –

回答

2
this.getCalendarData=function(){ 
     var getAppointmentsurl = './dbscripts/getAppointments.php'; 

      return $http({method: 'GET', url: getAppointmentsurl}).success(function(data) { 

       return data; 
      }); 


} 

這是asynchronus呼籲我們要像上面返回數據。

+0

作爲http返回承諾,我們必須在控制器中解決它。作爲 getCalendarData()。然後(功能(){ 這裏將您的數據 },函數(錯誤){ }) –

+1

打我吧:)我也建議使用$ q服務和解決/拒絕每個響應。 – zilj

+0

是的,您可以使用$ q服務使用defered.resove()。 –

0

當你把API調用作爲服務的方法,從服務返回的數據不會解決呢,所以在控制器中的服務回報只會是一個承諾

serviceName.getCalendarData().then(function(data){ 

    //Success data 
},function(){}); 

服務代碼必須返回像下面的代碼,在這裏你將會得到整個響應對象,

return $http({method: 'GET', url:getAppointmentsurl}); 

另一種方式來獲得直接解決了其他屬性的剝離是從這樣的服務返回的數據,

return $http({method: 'GET', url:getAppointmentsurl}).success(function(data){ 

    return data; 
}); 
0

爲了詳細說明阿卡什的正確答案,下面是一個應該如何工作的例子。

在您的視圖中,您應該添加邏輯以僅在存在問候時才顯示數據。即ng-if="hello"

控制器:

ServiceName.getCalendarData().then(function(response) { 
    $scope.hello = response; 
}); 

服務:

this.getCalendarData = function() { 
    return $http.get('path/to/response/').success(function(data) { 
    return data; 
    }); 
}