我无法将我的大脑包裹在异步请求的概念上。
我的视图有一个控制器,它从提供者创建一个对象实例:
va.controller('VaCtrl',function($scope,$shipment){
$scope.shipment = $shipment.Shipment();
});
提供者:
Shipment.provider('$shipment',function(){
this.$get = function($http){
function Shipment(){
}
Shipment.prototype.fetchShipment = function(){
var shipment = undefined;
$http.post('../sys/core/fetchShipment.php',{
// some data to POST
}).then(function(promise){
shipment = promise.data;
});
return shipment;
};
return {
Shipment: function(){
return new Shipment();
}
}
}
});
我的目标是从Shipment.prototype.fetchShipment()
我的控制器内部访问数据。我的做法:
$scope.fetchShipment = function(){
var shipment = $scope.shipment.fetchShipment();
console.log(shipment); // undefined
};
但是,这将返回未定义。
我读到了 $q,以及延迟、承诺和回调,现在我就像 WTF;我想做的就是将检索到的数据推送到我的控制器,最好的方法是什么?