2017-03-17 68 views
0

我試圖將結果從工廠拿到我的控制器。工廠不返回控制器中的對象

到目前爲止,我一直在失敗,工廠內部似乎一切正常,我可以使console.log的結果,它顯示得很好。

任何指針?

我此刻的工廠:

mainApp.factory('statusFinder', ['jsonQueryStations', 'timeConverter', function(jsonQueryStations, timeConverter){ 
    var findTheTime = timeConverter.getTime(); 
    var generator = function(){ 
     return jsonQueryStations.stationData().then(function(result){ 
     if (result.station[findTheTime]>result.station.Average){ 
     return "Station is busy"; 
     } else{ 
     return "Station is quiet"; 
     } 
     }); 
    } 
    return { 
    status: function(){ 
     return generator(); 
    } 
    } 
}]) 

而我此刻的控制器看起來像這樣:

mainApp.controller('stuff', ['$scope', 'statusFinder', function($scope, statusFinder){ 
var data = statusFinder.status(); 
$scope.testing = data; 
}]) 

回答

0

u能趕上從控制器,而不是廠家的承諾。只在工廠返回jsonQueryStations.stationData()

mainApp.factory('statusFinder', ['jsonQueryStations', 'timeConverter', function(jsonQueryStations, timeConverter){ 
    var generator = function(){ 
     return jsonQueryStations.stationData() 
    } 
    return { 
    status: function(){ 
     return generator(); 
    } 
    } 
}]) 

現在在控制器趕上承諾這樣

mainApp.controller('stuff', ['$scope', 'statusFinder', function($scope, statusFinder) { 
    var findTheTime = timeConverter.getTime(); 
    statusFinder.status().then(function(result) { 
     if (result.station[findTheTime] > result.station.Average) { 
      $scope.testing = "Station is busy"; 
     } else { 
      $scope.testing = "Station is quiet"; 
     } 
    }); 
}]) 
+0

謝謝你,我做了類似的事情以前,我只是想將我的功能出了控制器的現在,以整齊的事情了,那不是我能從工廠單獨做到的嗎? – Blimeys

+0

在你的問題http返回一個承諾和控制器dosn't等待承諾,因爲承諾從控制器捕獲。這是 –

+0

也應注意避免反模式的正確方法。它會在諾言中創造出另一個定製的諾言,它會讓一團糟 –