How to pause code till .then function is executed in AngularJS - angularjs

While I am loading an AngularJS file my code is getting executed completely before the code in .then function completes its execution. How to pause code till the code in .then function executes. I mean I want to make synchronous ajax calls, I used to use async: false in jQuery. I want to know how to do that in angularJS.
Thanks in advance
Below is my AngularJS code
var app = angular.module('myApp', [ ]);
app.controller("Ctrl",Ctrl);
function Ctrl($http){
var self=this
ajaxCall();
function ajaxCall(){
return $http.get('/getData/')
.then(function(data){
// this below alert should come before the last alert
alert(" should execute first then below alert")
self.data=data
})
}
alert("getting executed first")
}

Your ajaxCall() is returning a promise. So you can simply wait until it finished.
The $http API is based on the deferred/promise APIs exposed by the $q service. While for simple usage patterns this doesn't matter much, for advanced usage it is important to familiarize yourself with these APIs and the guarantees they provide.
AngularJS $http documentation
var app = angular.module('myApp', [ ]);
app.controller("Ctrl",Ctrl);
function Ctrl($http){
var self = this;
function ajaxCall(){
return $http.get('/getData/')
.then(function(data) {
// this below alert should come before the last alert
alert(" should execute first then below alert")
self.data = data;
}
);
}
// You can use .then here, because ajaxCall returns a promise
ajaxCall().then(function () {
alert("getting executed first");
})
}

What if you chain promises?
function Ctrl($http, $q){
var self = this;
ajaxCall();
function ajaxCall(){
return $http.get('/getData/')
.then(storeData)
.then(proceed);
}
function storeData(response) {
alert("1st");
self.data = response.data;
return $q.when(self.data);
}
function proceed(data) {
alert("2nd");
}
}

Related

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);
}
);
});

Execute function after inner $http call finishes - AngularJS

In my code I am calling this function loadAllOrders();. This is the skeleton of its implementation,
$scope.loadAllOrders = function() {
orderSvc.GetAllOrders().then(function(response) {
// Does a bunch of stuff here
});
}
GetAllOrders() uses a $http to get data from a database. loadAllOrders() then formats all the data and inserts them into an ng-repeat.
I want to be able to call a function when loadAllOrders() has finished. For example,
$scope.loadAllOrders().then(
//I am doing something
);
How can this be achieved?
You can write custom promise for loadAllOrders in angular JS
You have to inject $q service as a dependency on your controllers or service
$scope.loadAllOrders = function() {
var deferred = $q.defer();
orderSvc.GetAllOrders().then(function(response) {
// Does a bunch of stuff here
deferred.resolve(response);
});
return deferred.promise;
}
https://docs.angularjs.org/api/ng/service/$q
Hope this helps

Angular - set controller variable after service $http call

I'm finding it difficult making sense of all the differing blogs and examples out there on how to use a promise correctly in angular, so would appreciate some clarification from someone please.
Is using a callback passed in to the service get method to set the controller variable like this wrong?
In the Session service:
self.getSessions = function(callback) {
$http.get(self.urls.sessionsList).then(
function (response) {
callback(response.data);
},
function (response) {
// failure
}
);
};
from this controller:
.controller('SessionsController', ['Session', function(Session) {
var self = this;
self.sessions = [];
Session.getSessions(function(data) {
self.sessions = data;
});
}])
Q) Is using a callback passed in to the service get method to set the controller >>variable like this wrong?.
No, it is not wrong, but you can use the power of the promise and change your code to be something like below, where you can chain to the "then" method :
self.getSessions = function() {
return $http.get(self.urls.sessionsList);
}
and change your controller code to be:
.controller('SessionsController', ['Session', function(Session) {
var self = this;
self.sessions = [];
Session.getSessions().then(function(response) {
self.sessions = response.data;
});
}]);
Then, you can see that the caller can chain the to "then" and do more and more functionality,...
hope that helps.
Use Deffered promise is bad thing since es6 promise is released

how to prevent duplicated $http requests in AngularJS app?

I need to prevent sending the same request repeatedly to API before the previous request will give the response. I have found out some solutions. But, I don't want to disable the button while waiting for response because I have more API calls in my app.
I really need to do something in my $provider .config() .I found a way here(http://blog.codebrag.com/post/57412530001/preventing-duplicated-requests-in-angularjs).
But I need more clarification code. Any kind of reference about this is welcome.
Lets say you have $http in your controller.js file.
Many request to server
$http.get('/link/to/file.php');
Just one request to server, no matter how many times you will call this method:
$http.get('/link/to/file.php', {cache: true});
Example:
(function() {
'use strict';
angular
.module('yourModuleName')
.controller('DashboardCtrl', DashboardCtrl);
DashboardCtrl.$inject = ['$scope'];
function DashboardCtrl($scope) {
$scope.get = function () {
$http.get('/link/to/file.php', {cache: true}).then(function(response) {
// it will do GET request just once
// later you will get the same response from cacheFactory
})
}
}
}());
I would like to complement #VikasChauhan answer, however I do not have enough reputation to comment on his answer.
His code works great for me, except the part where he returns null. That causes Angular to throw a bunch of errors all over.
Instead of null, I simply reject the request:
return $q.reject(request);
Here's my function:
$httpProvider.interceptors.push(['$injector', '$q', function interceptors($injector, $q) {
return {
// preventing duplicate requests
request: function request(config) {
var $http = $injector.get('$http');
var _config = angular.copy(config);
delete _config.headers;
function isConfigEqual(pendingRequestConfig) {
var _pendingRequestConfig = angular.copy(pendingRequestConfig);
delete _pendingRequestConfig.headers;
return angular.equals(_config, _pendingRequestConfig);
}
if ($http.pendingRequests.some(isConfigEqual)) {
return $q.reject(request);
}
return config;
}
};
}
]);
Hope this helps other people.
You can create a function to cancel the first http request, when calling the another one on the button click.
Here is a reference that uses $q.defer() function that helped me on a similar issue:
http://odetocode.com/blogs/scott/archive/2014/04/24/canceling-http-requests-in-angularjs.aspx
In my project, i was facing this problem. I found a very useful working solution here
And implemented it inside the config:
function config($routeProvider, $httpProvider) {
$httpProvider.interceptors.push(['$injector', function interceptors($injector) {
// Manually injecting dependencies to avoid circular dependency problem
return {
// preventing duplicate requests
'request': function request(config) {
var $http = $injector.get('$http'),
copiedConfig = angular.copy(config);
delete copiedConfig.headers;
function configsAreEqual(pendingRequestConfig) {
var copiedPendingRequestConfig = angular.copy(pendingRequestConfig);
delete copiedPendingRequestConfig.headers;
return angular.equals(copiedConfig, copiedPendingRequestConfig);
}
if ($http.pendingRequests.some(configsAreEqual)) {
debugger;
return null;
}
return config;
}
}
}
]);
}

How to wait till the response comes from the $http request, in angularjs?

I am using some data which is from a RESTful service in multiple pages.
So I am using angular factories for that. So, I required to get the data once from the server, and everytime I am getting the data with that defined service. Just like a global variables. Here is the sample:
var myApp = angular.module('myservices', []);
myApp.factory('myService', function($http) {
$http({method:"GET", url:"/my/url"}).success(function(result){
return result;
});
});
In my controller I am using this service as:
function myFunction($scope, myService) {
$scope.data = myService;
console.log("data.name"+$scope.data.name);
}
Its working fine for me as per my requirements.
But the problem here is, when I reloaded in my webpage the service will gets called again and requests for server. If in between some other function executes which is dependent on the "defined service", It's giving the error like "something" is undefined. So I want to wait in my script till the service is loaded. How can I do that? Is there anyway do that in angularjs?
You should use promises for async operations where you don't know when it will be completed. A promise "represents an operation that hasn't completed yet, but is expected in the future." (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise)
An example implementation would be like:
myApp.factory('myService', function($http) {
var getData = function() {
// Angular $http() and then() both return promises themselves
return $http({method:"GET", url:"/my/url"}).then(function(result){
// What we return here is the data that will be accessible
// to us after the promise resolves
return result.data;
});
};
return { getData: getData };
});
function myFunction($scope, myService) {
var myDataPromise = myService.getData();
myDataPromise.then(function(result) {
// this is only run after getData() resolves
$scope.data = result;
console.log("data.name"+$scope.data.name);
});
}
Edit: Regarding Sujoys comment that
What do I need to do so that myFuction() call won't return till .then() function finishes execution.
function myFunction($scope, myService) {
var myDataPromise = myService.getData();
myDataPromise.then(function(result) {
$scope.data = result;
console.log("data.name"+$scope.data.name);
});
console.log("This will get printed before data.name inside then. And I don't want that.");
}
Well, let's suppose the call to getData() took 10 seconds to complete. If the function didn't return anything in that time, it would effectively become normal synchronous code and would hang the browser until it completed.
With the promise returning instantly though, the browser is free to continue on with other code in the meantime. Once the promise resolves/fails, the then() call is triggered. So it makes much more sense this way, even if it might make the flow of your code a bit more complex (complexity is a common problem of async/parallel programming in general after all!)
for people new to this you can also use a callback for example:
In your service:
.factory('DataHandler',function ($http){
var GetRandomArtists = function(data, callback){
$http.post(URL, data).success(function (response) {
callback(response);
});
}
})
In your controller:
DataHandler.GetRandomArtists(3, function(response){
$scope.data.random_artists = response;
});
I was having the same problem and none if these worked for me. Here is what did work though...
app.factory('myService', function($http) {
var data = function (value) {
return $http.get(value);
}
return { data: data }
});
and then the function that uses it is...
vm.search = function(value) {
var recieved_data = myService.data(value);
recieved_data.then(
function(fulfillment){
vm.tags = fulfillment.data;
}, function(){
console.log("Server did not send tag data.");
});
};
The service isn't that necessary but I think its a good practise for extensibility. Most of what you will need for one will for any other, especially when using APIs. Anyway I hope this was helpful.
FYI, this is using Angularfire so it may vary a bit for a different service or other use but should solve the same isse $http has. I had this same issue only solution that fit for me the best was to combine all services/factories into a single promise on the scope. On each route/view that needed these services/etc to be loaded I put any functions that require loaded data inside the controller function i.e. myfunct() and the main app.js on run after auth i put
myservice.$loaded().then(function() {$rootScope.myservice = myservice;});
and in the view I just did
ng-if="myservice" ng-init="somevar=myfunct()"
in the first/parent view element/wrapper so the controller can run everything inside
myfunct()
without worrying about async promises/order/queue issues. I hope that helps someone with the same issues I had.

Resources