2016-11-26 36 views
2
app.service('cityService',['$http',function($http){ 
this.get = function(){ 
     $http({ 
      method : 'get', 
      url : API_SERVER+'city/' 
     }).success(function(response){ 
      console.log(response); 
      return response; 
     }).error(function(response){ 
      console.log(response); 
     }); 
    }; 
} 

我想使用服務從服務器獲取數據,但問題是當我使用服務將數據存儲在作用域變量中時。我得到undefined。我接收數據,因爲數據顯示在控制檯中+當我添加到控制器中時服務也在工作,但數據不保存在任何變量中。我用$timeout延遲變量的檢查,但仍然沒有運氣。我還用.then()但它顯示undefined的服務時,我與服務添加...使用服務進行數據操作角

app.controller('Controller',['cityService',function(cityService){ 
$scope.temp = {}; 
$scope.temp = cityService.get(); 
}]); 

反正從業務數據傳遞到控制器? 注: 還試圖將所述數據存儲到服務變量和返回變量

this.var = '' 
this.get = function(){ 
    $http({ 
     method : 'get', 
     url : API_SERVER+'city/' 
    }).success(function(response){ 
     this.var = response 
     console.log(this.var); 
     return this.var; 
    }).error(function(response){ 
     console.log(response); 
    }); 
}; 

的數據被存儲到變量但最終不傳送到控制器的服務。 有什麼指導?你的服務

回答

0

this.get方法應返回從promise對象,以便調用者可以調用.then方法得到response到鏈中的承諾

服務

app.service('cityService', ['$http', function($http) { 
    this.get = function() { 
     return $http.get(API_SERVER + 'city/'); 
     //below would work but use upper one smaller version 
     //return $http({ 
     // method : 'get', 
     // url : API_SERVER+'city/' 
     //}); 
    }; 
}]); 

然後在訪問你的控制器內的數據,你可以放置.then功能,在它從它那裏得到響應。

此外,您錯過了在控制器DI陣列內添加$scope依賴項。

app.controller('Controller', ['cityService', '$scope', 
    function(cityService, $scope) { 
    $scope.temp = {}; 
    cityService.get().then(function(response) { 
     console.log(response) 
     $scope.temp = response.data; 
    }); 
    } 
]); 

Demo Here

+0

$ HTTP默認返回一個承諾......檢查angularjs文檔... 嘗試,但我得到的錯誤.....然後()不能設置爲未定義。 你可以用工作代碼顯示一個jsfiddle嗎?因爲我的工作不在工作 –

+0

@ScienCeSubject檢查出更新的答案&plunkr :) –

+0

它有點幫助...改變了我的邏輯,以實現我想要的...但仍然thnx幫助我 –

相關問題