2017-03-17 25 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

也应注意避免反模式的正确方法。它会在诺言中创造出另一个定制的诺言,它会让一团糟 –