Using an Angular Service for async HttpRequests - how to callback? - angularjs

I might be totally confused on how to properly use callback methods for ajax calls in angular. I have the following angular app and cannot figure out how to display the testUser object only after the ajax call is successfully completed.
I have an ng controller like so:
Controllers.controller('mainController', ['$scope','UserService', function ($scope, UserService) {
...
$scope.testUser = UserService.getTestUser();
...
}
The UserService is defined like so:
Services.service('UserService', function () {
...
this.getTestUser = function() {
...
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
return JSON.parse(xmlhttp.responseText);
}
};
xmlhttp.open('GET',url,false); //async set to false
xmlhttp.send();
}
...
}
Currently, the $scope.testUser is 'undefined' and blank on the page because it is being displayed before the ajax call completes. You can see in my service function that I have async set to false, but it doesnt seem to matter.
I've confirmed the ajax call does eventually return a populated user object. What am I missing to make the page display $scope.testUser only when its been successfully retrieved?

Thanks to Slava and georgeawg. I changed to the following and everything works great!
Controllers.controller('mainController', ['$scope','UserService', function ($scope, UserService) {
...
UserService.getTestUser.async().then(function(testUser) {
$scope.testUser = testUser;
};
...
}
And on the service side I have this:
Services.service('UserService', function ($http) {
...
this.getTestUser = {
async: function() {
var promise = $http.get(url).then(function(response) {
return response.data;
};
return promise;
}
}
Thank you!

Related

can't get the value in my controller after calling a promise in the service

i have a controller that calls a function in a service. this, in turn, calls a promise function inside the same service.
the problem is that i can't get the returned value in my controller.
the controller:
function mainFunctionInControlelr() {
some code here...
vm.evtHTTPFactory.getData() // calling the service
.then(function(response) {
console.log("the returned value is " + response.myReturned );
});
}
the service:
factory.getData = function(parm) {
return factory.getABC(parm); // calling another method in the same service
};
factory.getABC = function(parm) {
return $q(function(resolve, reject) {
$http.get(PltConfig.APIPath + '/v1/............', {
params: { inputParm: parm }
})
.success(function (response) {
resolve(response.data.myReturned);
return;
} )
});
};
the issue is that getData, inside the service, is calling getABC, also inside the service. something is lost in the process. I need to have "myReturned" in the controller.
what do i need to put in getData (in the service) to make things work?
thanks a lot.
I would use async await... like this:
in your function getData:
factory.getData = async function(parm) {
var data = await factory.getABC(parm);
return data;
};
in your function controller:
async vm.evtHTTPFactory.getData() {
var myResp = await vm.evtHTTPFactory.getData()
console.log(myResp)}
An example here: https://jsfiddle.net/hernangiraldo89/frv4L2jh/4/
I hope it helps you!

AngularJS call scope function to 'refresh' scope model

I've been struggling with this for a few days now and can't seem to find a solution.
I have a simple listing in my view, fetched from MongoDB and I want it to refresh whenever I call the delete or update function.
Although it seems simple that I should be able to call a previously declared function within the same scope, it just doesn't work.
I tried setting the getDispositivos on a third service, but then the Injection gets all messed up. Declaring the function simply as var function () {...} but it doesn't work as well.
Any help is appreciated.
Here's my code:
var myApp = angular.module('appDispositivos', []);
/* My service */
myApp.service('dispositivosService',
['$http',
function($http) {
//...
this.getDispositivos = function(response) {
$http.get('http://localhost:3000/dispositivos').then(response);
}
//...
}
]
);
myApp.controller('dispositivoController',
['$scope', 'dispositivosService',
function($scope, dispositivosService) {
//This fetches data from Mongo...
$scope.getDispositivos = function () {
dispositivosService.getDispositivos(function(response) {
$scope.dispositivos = response.data;
});
};
//... and on page load it fills in the list
$scope.getDispositivos();
$scope.addDispositivo = function() {
dispositivosService.addDispositivo($scope.dispositivo);
$scope.getDispositivos(); //it should reload the view here...
$scope.dispositivo = '';
};
$scope.removeDispositivo = function (id) {
dispositivosService.removerDispositivo(id);
$scope.getDispositivos(); //... here
};
$scope.editDispositivo = function (id) {
dispositivosService.editDispositivo(id);
$scope.getDispositivos(); //... and here.
};
}
]
);
On service
this.getDispositivos = function(response) {
return $http.get('http://localhost:3000/dispositivos');
}
on controller
$scope.addDispositivo = function() {
dispositivosService.addDispositivo($scope.dispositivo).then(function(){
$scope.getDispositivos(); //it should reload the view here...
$scope.dispositivo = '';
});
};
None of the solutions worked. Later on I found that the GET request does execute, asynchronously however. This means that it loads the data into $scope before the POST request has finished, thus not including the just-included new data.
The solution is to synchronize the tasks (somewhat like in multithread programming), using the $q module, and to work with deferred objects and promises. So, on my service
.factory('dispositivosService',
['$http', '$q',
function($http, $q) {
return {
getDispositivos: function (id) {
getDef = $q.defer();
$http.get('http://myUrlAddress'+id)
.success(function(response){
getDef.resolve(response);
})
.error(function () {
getDef.reject('Failed GET request');
});
return getDef.promise;
}
}
}
}
])
On my controller:
$scope.addDispositivo = function() {
dispositivosService.addDispositivo($scope.dispositivo)
.then(function(){
dispositivosService.getDispositivos()
.then(function(dispositivos){
$scope.dispositivos = dispositivos;
$scope.dispositivo = '';
})
});
};
Being my 'response' object a $q.defer type object, then I can tell Angular that the response is asynchronous, and .then(---).then(---); logic completes the tasks, as the asynchronous requests finish.

Loading data from angular service on startup

UPDATE
I am currently doing this, and I'm not sure why it works, but I don't think this is the correct approach. I might be abusing digest cycles, whatever those are.
First, I want to have the array navigationList be inside a service so I can pass it anywhere. That service will also update that array.
app.factory('ChapterService', [ 'ExtService', function(ExtService) {
var navigationList = [];
var getNavigation = function() {
ExtService.getUrl('navigation.json').then(function(data) {
angular.copy(data.navigationList, navigationList);
});
}
return{
getNavigation: getNavigation,
navigationList: navigationList,
}
}]);
Then in my controller, I call the service to update the array, then I point the scope variable to it.
ChapterService.getNavigation();
$scope.navigationList = ChapterService.navigationList;
console.log($scope.navigationList);
But this is where it gets weird. console.log returns an empty array [], BUT I have an ng-repeat in my html that uses $scope.navigationList, and it's correctly displaying the items in that array... I think this has something to do with digest cycles, but I'm not sure. Could anyone explain it to me and tell me if I'm approaching this the wrong way?
I have a main factory that runs functions and calculations. I am trying to run
app.factory('ChapterService', [ 'ExtService', function(ExtService) {
var navigation = {
getNavigationData : function () {
ExtService.getUrl('navigation.json').then(function(data) {
return data;
});
}
}
return: {
navigation: navigation
}
I did a console.log on the data before it gets returned and it's the correct data, but for some reason, I can't return it..
The ExtService that has the getUrl method is just the one that's typically used (it returns a promise)
In my controller, I want to do something like
$scope.navigation = ChapterService.navigation.getNavigationData();
in order to load the data from the file when the app initializes,
but that doesn't work and when I run
console.log(ChapterService.navigation.getNavigationData());
I get null, but I don't know why. Should I use app.run() for something like this? I need this data to be loaded before anything else is done and I don't think I'm using the best approach...
EDIT
I'm not sure if I should do something similar to what's being done in this jsfiddle, the pattern is unfamiliar to me, so I'm not sure how to re purpose it for my needs
My code for ExtService is
app.factory('ExtService', function($http, $q, $compile) {
return {
getUrl: function(url) {
var newurl = url + "?nocache=" + (new Date()).getTime();
var deferred = $q.defer();
$http.get(newurl, {cache: false})
.success(function (data) {
deferred.resolve(data);
})
.error(function (error) {
deferred.reject(error);
});
return deferred.promise;
}
}
});
EDIT 2
I'd like to separate the request logic away from the controller, but at the same time, have it done when the app starts. I'd like the service function to just return the data, so I don't have to do further .then or .success on it...
You are using promises incorrectly. Think about what this means:
var navigation = {
getNavigationData : function () {
ExtService.getUrl('navigation.json').then(function(data) {
return data;
});
}
}
getNavigationData is a function that doesn't return anything. When you're in the "then" clause, you're in a different function so return data only returns from the inner function. In fact, .then(function(data) { return data; }) is a no-op.
The important thing to understand about promises is that once you're in the promise paradigm, it's difficult to get out of it - your best bet is to stay inside it.
So first, return a promise from your function:
app.factory('ChapterService', [ 'ExtService', function(ExtService) {
var navigation = {
getNavigationData: function () {
return ExtService.getUrl('navigation.json');
}
}
return {
navigation: navigation
}
}])
Then use that promise in your controller:
app.controller('MyController', function($scope, ExtService) {
ExtService
.navigation
.getNavigationData()
.then(function(data) {
$scope.navigation = data;
});
})
Update
If you really want to avoid the promise paradigm, try the following, although I recommend thoroughly understanding the implications of this approach before doing so. The object you return from the service isn't immediately populated but once the call returns, Angular will complete a digest cycle and any scope bindings will be refreshed.
app.factory('ChapterService', [ 'ExtService', function(ExtService) {
var navigation = {
getNavigationData: function () {
// create an object to return from the function
var returnData = { };
// set the properties of the object when the call has returned
ExtService.getUrl('navigation.json')
.then(function(x) { returnData.nav = x });
// return the object - NB at this point in the function,
// the .nav property has not been set
return returnData;
}
}
return {
navigation: navigation
}
}])
app.controller('MyController', function($scope, ExtService) {
// assign $scope.navigation to the object returned
// from the function - NB at this point the .nav property
// has not been set, your bindings will need to refer to
// $scope.navigation.nav
$scope.navigation = ExtService
.navigation
.getNavigationData();
})
You are using a promise, so return that promise and use the resolve (.then) in the controller:
app.factory('ChapterService', [ 'ExtService', function(ExtService) {
var navigation = {
getNavigationData: function () {
return ExtService.getUrl('navigation.json'); // returns a promise
});
}
return: {
navigation: navigation
}
}
controller:
ChapterService
.navigation
.getNavigationData()
.then(function (data) {
// success
$scope.navigation = data;
}, function (response) {
// fail
});
This is a different approach, I don't know what your data looks like so I am not able to test it for you.
Controller
.controller('homeCtrl', function($scope, $routeParams, ChapterService) {
ChapterService.getNavigationData();
})
Factory
.factory('ChapterService', [ 'ExtService', function(ExtService) {
function makeRequest(response) {
return ExtService.getUrl('navigation.json')
}
function parseResponse(response) {
retries = 0;
if (!response) {
return false;
}
return response.data;
}
var navigation = {
getNavigationData: function () {
return makeRequest()
.then(parseResponse)
.catch(function(err){
console.log(err);
});
}
}
return navigation;
}])

Angularjs sharing data between controllers

I have a service that fetches some client data from my server:
app.factory('clientDataService', function ($http) {
var clientDataObject = {};
var cdsService = {
fetch: function (cid) {
//$http returns a promise, which has a then function, which also returns a promise
var promise = $http.get('/clients/stats/' + cid + '/').then(function (response) {
// The then function here is an opportunity to modify the response
console.log(response);
// The return value gets picked up by the then in the controller.
clientDataObject = {'data': response.data, 'currentClientID': cid};
return clientDataObject;
});
// Return the promise to the controller
return promise;
}
};
return cdsService;
});
Then in one controller I do:
//get stats
clientDataService.fetch($scope.id).then(function (response) {
$scope.client_data = {
'statistics': response.data
}
});
Which all works very well. However, I'm trying to do a watch from another controller on that service to update it's scope when the data changes, rather then having to re-kick off the http request:
$scope.$watch('clientDataService.clientDataObject', function (cid) {
alert(cid);
});
I'm just alerting for now, but it never ever triggers. When the page initially loads, it alerts "undefined". I have no errors in the console and all the $injects are fine, but it never seems to recognize that data has changed in the service. Am I doing something wrong in the watch?
Many thanks
Ben
clientDataService.clientDataObject is not part of your controller's scope, so you can't watch for changes on that object.
You need to inject the $rootScope into your service then broadcast the changes to the controllers scopes.
app.factory('clientDataService', function ($rootScope, $http) {
var clientDataObject = {};
var cdsService = {
fetch: function (cid) {
var promise = $http.get('/clients/stats/' + cid + '/').then(function (response) {
// The then function here is an opportunity to modify the response
console.log(response);
// The return value gets picked up by the then in the controller.
clientDataObject = {'data': response.data, 'currentClientID': cid};
$rootScope.$broadcast('UPDATE_CLIENT_DATA', clientDataObject);
return clientDataObject;
});
// Return the promise to the controller
return promise;
}
};
return cdsService;
});
Then in the controller you can listen for the change using:
$scope.$on('UPDATE_CLIENT_DATA', function ( event, clientDataObject ) { });
Another approach can be:
define new service
app.factory('DataSharingObject', function(){
return {};
}
include this new service in controller where we want to store the data
app.factory('clientDataService', function ($http, DataSharingObject) {
DataSharingObject.sharedata = ..assign it here
}
include this new service in controller where we want to access the data
app.factory('clientReceivingService', function ($http, DataSharingObject) {
..use it here... = DataSharingObject.sharedata
}

AngularJS $timeout within a resource factory

I currently have an angular application which upon user login calls a service to begin a server call to refresh a count, only allowing for a server side return if the user is authenticated.
resource.approvalsCount = 0;
var approvalsCountTimer;
resource.getApprovalsCount = function (username) {
return resource.query({
username: username,
q: 'approvalsCount'
}).$then(function (response) {
resource.approvalsCount = response.data.count;
approvalsCountTimer = $timeout(resource.getApprovalsCount, 3000);
return resource.approvalsCount;
});
};
When a user logs out I am attempting to cancel that counter otherwise the server will return a 401 unauthorized error by calling a function based on the resource:
resource.cancelTimers = function () {
$timeout.cancel(approvalsCountTimer);
}
The issue is that the counter continues to run even after I call the cancel upon the $timeout which returns a 401 from the server. Console logging out the return the cancel function returns true (cancel has worked). I have tried several different placements of the begin of the $timeout to no avail, is there a way to ensure that all of the $timeouts are canceled? I don't understand what I am missing in this configuration.
EDIT
angular.module('resources.approvals.approvals', ['ngResource'])
.factory('Approvals', ['$timeout', '$resource', function ($timeout, $resource) {
var resource = $resource('/approvals/:username/:requestID', {}, {
'update': {
method: 'PUT'
}
});
resource.approvalsCount = 0;
var approvalsCountTimer;
resource.getApprovalsCount = function (username) {
return resource.query({
username: username,
q: 'approvalsCount'
}).$then(function (response) {
resource.approvalsCount = response.data.count;
approvalsCountTimer = $timeout(resource.getApprovalsCount, 3000);
return resource.approvalsCount;
});
};
resource.cancelTimers = function () {
$timeout.cancel(approvalsCountTimer);
};
return resource;
}]);
I think your code looks good. It got to be something else.
I simplified a bit and you can see it on the demo. it simulates the http call every half second and the cancelTimes will be called in 4 seconds.
app = angular.module('app', []);
app.factory('Approvals', ['$timeout', function ($timeout) {
var resource = {};
resource.approvalsCount = 0;
var approvalsCountTimer;
resource.getApprovalsCount = function (username) {
console.log(approvalsCountTimer);
approvalsCountTimer = $timeout(resource.getApprovalsCount, 500);
};
resource.cancelTimers = function () {
console.log("stopped");
$timeout.cancel(approvalsCountTimer);
};
return resource;
}]);
function Ctrl($scope, $timeout, Approvals) {
Approvals.getApprovalsCount();
$timeout(Approvals.cancelTimers, 4000)
}

Resources