Async Service
In several places in my AngularJS app I need to fetch some basic value from a webservice. That is a somewhat legacy call and takes a few seconds to make. Any changes to this data is saved as soon as they are made and no other call to this is needed in the session. I was thinking the best way was to make the call at app start, and do it in the background, later when a user would move to a dependent state it should already be resolved. I'm not sure if this is a good idea or not and two questions about this come to mind. 1) Where should I initialize the service so that it happens right of the bat, but doesn't hold back the resolving of the MainCtrl etc. 2) If a dependent state is called before the the service is fully initialized (for example refresh in a dependent state) I would need to wait for the resolve, could I grab the promise somehow at that state, even if the service already started initializing (perhaps storing the promise object somewhere)?
by IngoVals
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.0/angular-ui-router.js"></script>
<div ui-view></div>
JavaScript
/* myApp module */
var myApp = angular.module('myApp', ['ui.router'])
.config(['$stateProvider', function ($stateProvider) {
$stateProvider.state('mainstate', {
url: "/",
controller: 'mainstateCtrl',
template: '<div><h1>mainstate</h1><h3>{{message}}</h3><button ng-click="goto()">Go to dependant state</button></div>'
})
.state('dependantstate', {
controller: 'dependantstateCtrl',
resolve: {
data: function (serviceWithLongCall) {
return serviceWithLongCall.call();
},
halfvalue: function (data, halfingservice) {
return halfingservice.halfer(data.value);
}
},
template: '<div><h1>Dependant State</h1><p>full value = {{value}}</p><p>half value = {{halfvalue}}</p><button ng-click="goto()">Go to Main</button></div>'
});
}]).run(function ($rootScope, $state, $stateParams, serviceWithLongCall) {
serviceWithLongCall.call();
})
.controller('MyAppCtrl', function ($scope, $state /*, $stateParams*/ ) {
console.log("MyAppCtrl initialized!");
$state.go("mainstate");
});
function mainstateCtrl($scope, $state) {
$scope.message = 'welcome',
$scope.goto = function () {
console.log("going to dependant state");
$scope.message = 'prepare to wait while resolving'
$state.go('dependantstate');
};
}
function dependantstateCtrl($scope, $state, data, halfvalue) {
console.log(data.value);
console.log(halfvalue);
$scope.value = data.value;
$scope.halfvalue = halfvalue;
$scope.goto = function () {
$state.go('mainstate');
};
}
myApp.factory('serviceWithLongCall', function ($q, $timeout) {
var data = {}
var hasStarted = false;
var deferred = $q.defer();
var serviceWithLongCall = {
call: call
};
return serviceWithLongCall;
function call() {
if (!hasStarted) {
hasStarted = true;
...