AngularJS promise and prevent redundant async calls - angularjs

I have a wcf service method that gets some data and I call it using Microsoft Ajax library.
To share this data I create a dataService, and many controllers use this service.
I want every controller to get the same data after first call of getData is done, unless somebody need to refresh data and set forceRefresh to true.
My code fails because with the initialize of application 3 controler call dataService.getData and for all there start a new request. How can I make wait dataService.getData calls until the first one is finished and get same result for other subsequent ones..
angular.module('app', []).factory('dataService', function ($q) {
var data= [];
var getData= function (forceRefresh) {
console.log('getFolders called: ', reports.length);
var deferred = $q.defer();
if (forceRefresh || data.length < 1) {
WcfService.GetData(function(result) {
data= result;
deferred.resolve(data);
}, function(ex) { console.log(ex); });
} else {
deferred.resolve(reports);
}
return deferred.promise;
};
return {
getData: getData
};
});

One way would be to cache the promise, rather than the data, so it gets cached when it is created and not when the data arrives. After all, this sounds like your use case.
angular.module('app', []).factory('dataService', function ($q) {
var deferred = null;
var getData= function (forceRefresh) {
console.log('getFolders called: ', reports.length);
if(!forceRefresh && deferred) return deferred.promise;
deferred = $q.defer();
WcfService.GetData(
function(result) { deferred.resolve(data); }, // I'd promisify at a
function(ex){ deferred.reject(ex); } // higher level probably
);
return deferred.promise;
};
return {
getData: getData
};
});

how about setting a global flag in the $rootscope when a controller is querying for data, which can be checked before fetching the data by all the controllers, hence, avoiding redundant calls. The same flag can be put down when any of the controller has the promise fulfilled and data has been fetched, which can then be shared amongst all the controllers.

I found exactly what I search for
Promise queue for AngularJS services
http://inspectorit.com/tips-tricks/promise-queue-for-angularjs-services/

Related

AngularJS : How to initialize service with async data and inject it into depend service

I have a similar situation like in AngularJS : Initialize service with asynchronous data, but I need to inject my base service with asynchronous data into depend services. It looks like this:
Base service:
angular.module('my.app').factory('baseService', baseService);
baseService.$inject = ['$http'];
function baseService($http) {
var myData = null;
var promise = $http.get('api/getMyData').success(function (data) {
myData = data;
});
return {
promise: promise,
getData: function() {
return myData;
}};
}
Dependent service (in which I inject base service)
angular.module('my.app').factory('depentService', depentService);
depentService.$inject = ['baseService'];
function depentService(baseService) {
var myData = baseService.getData();
....
return {...};
}
Route:
angular.module('my.app', ["ngRoute"])
.config(function ($routeProvider) {
$routeProvider.when('/',
{
resolve: {
'baseService': function (baseService) {
return baseService.promise;
}
}
});
});
But nothing happens, baseService.getData() still returns null (coz async api call still in progress). Seems like my ngRoute config is invalid, but I cant indicate any controller/template into it.
How can I correctly resolve my baseService and get data in Depend service?
Dependent services should work with promises and return promises:
angular.module('my.app').factory('depentService', depentService);
depentService.$inject = ['baseService'];
function depentService(baseService) {
̶v̶a̶r̶ ̶m̶y̶D̶a̶t̶a̶ ̶=̶ ̶b̶a̶s̶e̶S̶e̶r̶v̶i̶c̶e̶.̶g̶e̶t̶D̶a̶t̶a̶(̶)̶;̶
var promise = baseService.promise;
var newPromise = promise.then(function(response) {
var data = response.data;
//...
var newData //...
return newData;
});
return newPromise;
}
To attempt to use raw data risks race conditions where the dependent service operates before the primary data returns from the server.
From the Docs:
The .then method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback (unless that value is a promise, in which case it is resolved with the value which is resolved in that promise using promise chaining).
— AngularJS $q Service API Reference - The Promise API

Execute $http requests in a particular order

I have about 5 requests that are made when my view loads. This is for an edit form:
var reqA = function() {...};
var reqB = function() {...};
var reqC = function() {...};
var reqD = function() {...};
var reqE = function() {...};
Now I want reqA() and reqB() to load asynchronously and if possible return a single promise.
reqC() and reqD() should only load after reqA() and reqB() have finished and executed their promise.
reqE() should only load after reqC() and reqD().
This is what I want to do, however I have no idea how to go about it. I can load them all asynchronously or one after another by chaining promises but not in the way I want.
If your functions all use the $http provider, it is easy to accomplish. You will want to modify your functions to return the result of the $http call like this
function reqA() {
return $http.get(...);
}
Now that they are returning promises, you can easily use the $q provider to orchestrate your requests:
$q.all([reqA(), reqB()])
.then( () =>
$q.all([reqC(), reqD()])
.then(() => reqE())
);
For regular JS (non ES6):
$q.all([reqA(), reqB()])
.then(function() {
$q.all([reqC, reqD()])
.then(function() {
reqE();
});
});
If you don't want to return the result of $http in your functions, you will need to set them up to return a promise in one way or the other:
function reqA() {
var deferred = $q.defer();
... your request code ...
// call this if everything is ok
deferred.resolve();
// call this if there was an error
deferred.reject();
return deferred.promise;
}
Here is an example that you can take a look at that might make it clearer. It makes use of Promise which is globally available in almost all javascript environments (excluding IE and older node versions).
angular
.module('example', [])
.run(function($q) {
function requestOne() {
return $q.when("one")
}
function requestTwo() {
return $q.when("two")
}
function requestThree() {
return $q.when("three")
}
function requestFour() {
return $q.when("four")
}
function requestFive() {
return $q.when("five")
}
$q
.all([requestOne(), requestTwo()])
.then(function(responses){
console.log(responses[0] === "one");
console.log(responses[1] === "two");
return $q.all([requestThree(), requestFour()]);
})
.then(function(nextResponses){
console.log(nextResponses[0] === "three");
console.log(nextResponses[1] === "four")
return requestFive();
})
.then(function(lastResponse){
console.log(lastResponse === "five")
})
});
angular.element(document).ready(function() {
angular.bootstrap(document, [ 'example' ]);
});
I assume that you are using angular 1, if you aren't there Promise is available in the global scope in almost all environments.

Angular directive without timeout service does not work

In angularJS, I have written a directive to display data. This data is fetched by a http service from remote database.
If I apply below timeout service in code, then result is displayed on the html page as http service returns in one second.
$timeout(function () {
$scope.treeRoot = $scope.$eval('serviceResult') || {};
}, 1000);
If i do not use timeout service, then page does not show any data because $scope.treeRoot is empty e.g.
$scope.treeRoot = $scope.$eval('serviceResult') || {};
In production, the http service can take time more than one second to return, is there any generic solution.
You should use Angular's promises or $http service which allows to return a promise.
After the promise, e.g. $http request, is resolved, you can populate $scope.treeRoot with the results.
Let me know if that helps.
AS suggested in one answer you have to use the $http promises and capture the result in response.
Here is an example with some code.
Service:
app.factory('myService', ['$http',
function($http){
var obj = {};
obj.get = function (q) {
return $http.get('/your_get_url')
};
obj.post = function (q, object) {
return $http.post('/your_post_url', object)
};
return obj;
}
]);
In your controller,
allControllers.controller('changePasswordController', ['$scope','myService',
function($scope,myService) {
myService.get().then(function (result) {
$scope.treeRoot = 'use your result here'
},function error(result)
{
console.log(result)
})
}
])
This replaces your timeout issue.

AngularJS +how to wait for task to finish before running next task

I have still problems with my database, but I found out, that the problems come from the fact, that opening the database takes some time, but the app is not waiting till this task has finished.
Is there a way to make angular wait till the database is opened correctly before it starts the next task?
Thanks,
Christian.
Update: 2016-08-08 - 03:13 pm
Thanks for all the answers. As I can see, my first idea with promises ($q) was right, but:
My app has an app.js, which is my main file. It only calls the InitDB. This should open the database. Then it should call the CreateTables, this creates the table, if it doensn't exist.
The rest of my app is splitted in 4 pages (templates). Every page has it's own controller.
So the idea was to init the db, to create the table, and then work with the database, but used over different controllers.
This won't work, because I would always need to put all of my stuff in the .then() of my initDB in the app.js???
This is my first AngularJS app, maybe this is the reason why I do a lot of mistakes...
Thanks,
Christian.
One of the core concepts of Angular is working with services/factories. There is ample documentation and blogs about how these work and how to use them, but the basic idea is that these are singleton "controllers" that handle shared data and methods across your entire application. Used in combination with promises, you can easily create a service that will manage communications with your database.
angular
.module('myApp')
.service('DBService', DBService)
.controller('Ctrl1', Ctrl1)
.controller('Ctrl2', Ctrl2)
.controller('Ctrl3', Ctrl3)
.controller('Ctrl4', Ctrl4);
DBService.$inject = ['$q'];
function DBService($q) {
var DBService = this;
var DBServiceDeferred = $q.defer();
DBService.ready = DBServiceDeferred.promise;
// a service is only initialized once, so this will only ever be run once
(function() {
init();
})();
function init() {
// you can use promise chaining to control order of events
// the chain will halt if any function is rejected
initDB()
.then(createTablesUnlessExist)
.then(setDbReady);
}
function initDB() {
var deferred = $q.defer();
// simulate async db initialization
$timeout(function() {
deferred.resolve();
// or reject if there is an error
// deferred.reject();
}, 5000);
return deferred.promise;
};
function createTablesUnlessExist() {
//create tables if needed (only happens once)
var deferred = $q.defer();
// simulate async table creation
$timeout(function() {
deferred.resolve();
// or reject if there is an error
// deferred.reject();
}, 5000);
return deferred.promise;
}
function setDbReady() {
DBServiceDeferred.resolve();
}
}
Now you have your DB setup and you don't have to worry about it anymore. You can access the DB from any controller using the service. None of the queries will run until the DB has been initialized and the tables have been created.
Ctrl1.$inject = ['DBService', '$q'];
function Ctrl1(DBService, $q) {
$q.when(DBService.ready).then(function() {
DBService.conn.query("Select something");
});
}
Ctrl2.$inject = ['DBService', '$q'];
function Ctrl2(DBService, $q) {
$q.when(DBService.ready).then(function() {
DBService.conn.query("Select something");
});
}
Ctrl3.$inject = ['DBService', '$q'];
function Ctrl3(DBService, $q) {
$q.when(DBService.ready).then(function() {
DBService.conn.query("Select something");
});
}
Ctrl4.$inject = ['DBService', '$q'];
function Ctrl4(DBService, $q) {
$q.when(DBService.ready).then(function() {
DBService.conn.query("Select something");
});
}
Angular provides a service $q. A service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing. Please refer the documentation https://docs.angularjs.org/api/ng/service/$q for the same.
$q basically revolves around the concepts of promises. Promises in AngularJS are provided by the built-in $q service.
Write a method that check if connection is established or not...which returns true or false.
app.controller('MainCtrl', function($scope, httpq) {
http.get('server call method')
.then(function(data) {
if(data.conn==true)
// do what u want
//write other calls
})
.catch(function(data, status) {
console.error('error', response.status, response.data);
})
});
you can use $q library
example:
app.service("githubService", function ($http, $q) {
var deferred = $q.defer();
this.getAccount = function () {
return $http.get('https://api.github.com/users/haroldrv')
.then(function (response) {
// promise is fulfilled
deferred.resolve(response.data);
// promise is returned
return deferred.promise;
}, function (response) {
// the following line rejects the promise
deferred.reject(response);
// promise is returned
return deferred.promise;
})
;
};
});
using above service:
app.controller("promiseController", function ($scope, $q, githubService) {
githubService.getAccount()
.then(
function (result) {
// promise was fullfilled (regardless of outcome)
// checks for information will be peformed here
$scope.account = result;
},
function (error) {
// handle errors here
console.log(error.statusText);
}
);
});

Controlling order of execution in angularjs

I have inherited an angular app and now need to make a change.
As part of this change, some data needs to be set in one controller and then used from another. So I created a service and had one controller write data into it and one controller read data out of it.
angular.module('appRoot.controllers')
.controller('pageController', function (myApiService, myService) {
// load data from API call
var data = myApiService.getData();
// Write data into service
myService.addData(data);
})
.controller('pageSubController', function (myService) {
// Read data from service
var data = myService.getData();
// Do something with data....
})
However, when I go to use data in pageSubController it is always undefined.
How can I make sure that pageController executes before pageSubController? Or is that even the right question to ask?
EDIT
My service code:
angular.module('appRoot.factories')
.factory('myService', function () {
var data = [];
var addData = function (d) {
data = d;
};
var getData = function () {
return data;
};
return {
addData: addData,
getData: getData
};
})
If you want your controller to wait untill you get a response from the other controller. You can try using $broadcast option in angularjs.
In the pagecontroller, you have to broadcast your message "dataAdded" and in the pagesubcontroller you have to wait for the message using $scope.$on and then process "getData" function.
You can try something like this :
angular.module('appRoot.controllers')
.controller('pageController', function (myApiService, myService,$rootScope) {
// load data from API call
var data = myApiService.getData();
// Write data into service
myService.addData(data);
$rootScope.$broadcast('dataAdded', data);
})
.controller('pageSubController', function (myService,$rootScope) {
// Read data from service
$scope.$on('dataAdded', function(event, data) {
var data = myService.getData();
}
// Do something with data....
})
I would change your service to return a promise for the data. When asked, if the data has not been set, just return the promise. Later when the other controller sets the data, resolve the previous promises with the data. I've used this pattern to handle caching API results in a way such that the controllers don't know or care whether I fetched data from the API or just returned cached data. Something similar to this, although you may need to keep an array of pending promises that need to be resolved when the data does actually get set.
function MyService($http, $q, $timeout) {
var factory = {};
factory.get = function getItem(itemId) {
if (!itemId) {
throw new Error('itemId is required for MyService.get');
}
var deferred = $q.defer();
if (factory.item && factory.item._id === itemId) {
$timeout(function () {
deferred.resolve(factory.item);
}, 0);
} else {
$http.get('/api/items/' + itemId).then(function (resp) {
factory.item = resp.data;
deferred.resolve(factory.item);
});
}
return deferred.promise;
};
return factory;
}

Resources