angularjs - recursive http request javascript -
i'm making single page app using angularjs. want have pending http request server, server responds, send http request. wrote recursive function statecheck(), code gets stuck inside of function , never returns factory , never updates view.
how have these http requests pending in app without getting stuck inside of infinite loop?
define([ 'angular', 'app', 'angularroute', ], function (angular, app) { 'use strict'; app.config(function ( $httpprovider) { /* angular automatically adds header request, preventing being able make requests server on 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; }]); });
the problem lies in way initialized factory.getequipmentstate
. initialization invoking /get
request definition, accessing resolved promise within statecheck()
confirms first invocation not next.
to solve problem can structure equipmentservice
this:
factory('equipmentservice', ['$http', '$rootscope', function($http, $rootscope) { var factory = { getequipmentstate: function() { return this.equipmentstate; }, 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 () { $http.get($rootscope.backendserver+'/equipment/state') .success(function (data) { factory.setequipmentstate(data.data); }) .then(statecheck); } statecheck(); return factory; }])
Comments
Post a Comment