【发布时间】:2014-06-27 17:38:52
【问题描述】:
我正在使用 AngularJS 制作单页应用程序。我想不断地向服务器发送一个待处理的 http 请求,所以一旦服务器响应,就发送另一个 http 请求。我写了递归函数 stateCheck(),但我的代码卡在函数内部,永远不会返回工厂,也永远不会更新视图。
如何让这些 http 请求在我的应用程序中不断挂起,而不会陷入无限循环?
define([
'angular',
'app',
'angularRoute',
], function (angular, app) {
'use strict';
app.config(function ( $httpProvider) {
/* Angular automatically adds this header to the request,
preventing us from being able to make requests to the server on another port */
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}).factory('equipmentService', ['$http', '$rootScope', function($http, $rootScope) {
var factory = {
getEquipmentState: $http.get($rootScope.backendServer+'/equipment/state'),
setEquipmentState: function(state){
this.equipmentState = state.state;
console.log('equipment state', this.equipmentState);
redirectState(this.equipmentState);
}
}
var redirectState = function (state) {
switch(state) {
case 'Active':
$location.path('/active');
break;
case 'Review':
$location.path('/review');
break;
default:
// don't change views
}
}
function stateCheck () {
factory.getEquipmentState
.then(function (data) {
factory.setEquipmentState(data.data);
})
.then(stateCheck);
}
stateCheck();
return factory;
}]);
});
【问题讨论】:
标签: javascript angularjs http recursion