我正在使用AngularJS调用http服务,该服务返回对象中的某些打开时间。我不明白为什么在我的控制器中,console.log被打印4次而不是4次。有人可以向我解释吗?
这是我的服务/工厂代码:
myApp.factory('BookingFactory', ['$http', '$q', function($http, $q) {
var deferredTime = $q.defer();
return {
GetDealerLocationTimeList: function(websiteId) {
return $http.get('/d/GetDealerLocationTimes?website_id=' + websiteId)
.then(function(response) {
deferredTime.resolve(response.data);
dealerLocationTimeList.push(response.data);
return deferredTime.promise;
}, function(error) {
deferredTime.reject(response);
return deferredTime.promise;
});
}
}
}]);
这是我调用服务的控制器代码:
var promise = BookingFactory.GetDealerLocationTimeList(website_id);
promise.then(
function(da) {
$scope.dealerLocationTimeList = da;
console.log($scope.dealerLocationTimeList);
},
function(error) {
$log.error('failure loading dealer associates', error);
}
);
最佳答案
此代码中有很多错误> <
如果要使用deferred,则应为以下代码:
myApp.factory('BookingFactory', ['$http', '$q', function($http, $q) {
return {
GetDealerLocationTimeList: function(websiteId) {
var deferredTime = $q.defer(); // deferred should be created each time when a function is called. It can only be consumed (resolved/rejected) once.
/* return - don't need to return when you already creating a new deferred*/
$http.get('/d/GetDealerLocationTimes?website_id=' + websiteId)
.then(function(response) {
deferredTime.resolve(response.data);
// dealerLocationTimeList.push(response.data);
}, function(error) {
deferredTime.reject(error); // it should be 'error' here because your function argument name says so...
});
return deferredTime.promise; // promise is returned as soon as after you call the function, not when the function returns
}
}
}]);
但是,如果内部函数本身是一个Promise(例如
$http.get
),则返回Promise是一种更好的做法。myApp.factory('BookingFactory', ['$http', '$q', function($http, $q) {
return {
GetDealerLocationTimeList: function(websiteId) {
// no need to create new deferred anymore because we are returning the promise in $http.get
return $http.get('/d/GetDealerLocationTimes?website_id=' + websiteId)
.then(function(response) {
// dealerLocationTimeList.push(response.data);
return response.data; // return the data for the resolve part will make it available when the outer promise resolve
}/* this whole part should be omitted if we are not doing any processing to error before returning it (thanks @Bergi)
, function(error) {
return $q.reject(error); // use $q.reject to make this available in the reject handler of outer promise
}*/);
// no need to return promise here anymore
}
}
}]);
您可以看到我也评论了您的
dealerLocationTimeList.push(response.data)
。在这种情况下,您应该将数据推送到外层(在promise.then中)的作用域变量中,因为在工厂中没有DealerLocationTimeList。promise.then(
function(da) {
// you might want to do an isArray check here, or make sure it is an array all the time
$scope.dealerLocationTimeList.push(da);
console.log($scope.dealerLocationTimeList);
},
...
);
关于javascript - AngularJS http promise 触发4次,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33337445/