Handle simultaneous get calls in angularjs - angularjs

My angular application is divided into 4 modules and all modules require user details so I am calling getUser method from each of the module. So when my application loads all 4 modules hit the getUser API simultaneously resulting in 4 get requests on server. How can I prevent this ? I am using singleton pattern in my getUser method so once my user gets loaded it will simply serve the user from an object. But that does not solves the problem if all modules request for the user simultaneously.
My code looks like this
getUser() {
let defer = this.q.defer();
if (!this.user) {
this.http.get(`${this.config.apiHost}users`)
.success(result => {
this.user = result;
this.rootScope.$broadcast('userFound', this.user);
defer.resolve(this.user);
})
.error(err => defer.reject(err))
}
else {
defer.resolve(this.user);
this.rootScope.$broadcast('userFound', this.user);
}
return defer.promise;
}

By storing the current request in a variable the call to UserService.get will return the same request promise.
Then when the promise resolves, it will resolve to all your modules.
angular.module('app').service('UserService', function ($http) {
var self = this;
var getRequestCache;
/**
* Will get the current logged in user
* #return user
*/
this.get = function () {
if (getRequestCache) {
return getRequestCache;
}
getRequestCache = $http({
url: '/api/user',
method: 'GET',
cache: false
}).then(function (response) {
// clear request cache when request is done so that a new request can be called next time
getRequestCache = undefined;
return response.data;
});
return getRequestCache;
};
});

You are using ui-router for the routing. You can then use this to resolve the user when landing on the page.
In your routing config :
$stateProvider
.state('myPage', {
url: '/myPage',
templateUrl: 'myPage.html',
controller: 'myCtrl',
resolve: {
userDetails: ['UserService', function(UserService) {
return UserService.getUserDetails();
}],
}
})
In your controller
angular.module('myModule')
.controller('myCtrl', ['userDetails', function(userDetails) {
console.log(userDetails);
}];
This will load the user details while loading the page.

I solved this problem by using defer object as a global object so that it only gets initialised once.

Related

My AngularJS Service not Updating when User Click link with different $routeParams

I'm using a service in angularJS which gets a JSON object and passes it to a controller whenever a user clicks a specific link, /match/id-:matchId', it uses the $routeParams of the :matchId to select which JSON object to request.
The problem it once the user clicks one /match/id-:matchId' link and then tries going to another match with a different ID in the URL, the JSON object does not change, it remains the same. If the user refreshed the page, then they will get the correct JSON object on the page.
Here's the code:
var app = angular.module('app', ['ngRoute']); // TODO: 'ngAnimate', 'ui.bootstrap'
app.config(['$routeProvider','$locationProvider', function($routeProvider, $locationProvider){
$routeProvider
.when('/', {
templateUrl: '/app/static/home.html',
controller: 'mainController as mainCtrl'
})
.when('/match/id-:matchId', {
templateUrl: '/app/components/match/matchView.html',
controller: 'matchController as matchCtrl'
});
// use the HTML5 History API
$locationProvider.html5Mode(true);
}]);
app.controller('matchController', ['$routeParams', 'matchService', function ($routeParams, matchService) {
var matchCtrl = {};
var promise = matchService.getMatch($routeParams.matchId);
promise.then(function (data)
{
matchCtrl.match = data;
});
}])
app.service("matchService", function ($http, $q)
{
var deferred = $q.defer();
function getMatch(matchId) {
var url = 'https://jsonplaceholder.typicode.com/posts/' + matchId;
return $http({
method: 'GET',
// cache: true,
url: url,
headers: {
'Content-Type': 'application/json;charset=UTF-8'
}
}).
then(function(response) {
//your code when success
// lgTblCtrl.amateurTable = data;
deferred.resolve(response);
console.log('SUCCESS!');
}, function(response) {
//your code when fails
console.log('ERROR!');
deferred.reject(response);
});
return deferred.promise;
}
this.getMatch = getMatch;
})
There are no console errors but when I put breakpoints in the chrome source panel I can see that when the user refreshes the page the code get's called in a different order. This is the order specific lines of code are run depending on how the user landed on a page, by clicking a button or refreshing the page:
Browser Refresh
var promise = matchService.getMatch($routeParams.matchId);
return deferred.promise;
deferred.resolve(response);
matchCtrl.match = data;
Click On A Link
var promise = matchService.getMatch($routeParams.matchId);
return deferred.promise;
matchCtrl.match = data;
deferred.resolve(response);
I'm new to AngularJS, What am I missing here?
This looks like an issue with your deceleration of your 'deferred' variable. The promise is returned correctly the first time, but then it resolves right away whenever the function is called again as the promise is resolved the first time.
Try the following to see if it fixes your issue, moving the declaration of the promise into the function:
app.service("matchService", function ($http, $q) {
function getMatch(matchId) {
var deferred = $q.defer();
var url = 'https://jsonplaceholder.typicode.com/posts/' + matchId;
return $http({
method: 'GET',
// cache: true,

Getting user data in AngularJS on authentication and on page refresh

I've made an AuthService that should help me take care of all authentication matters like logging in, registering, getting user data from server etc.
I am looking for a solution that runs only on login, on page refresh and when triggered to refresh get the user data from the service and make it available on the controllers that i include the service to. I would like to have something like vm.user = AuthService.getUserData() and this returns the session variable from the service. Something like this:
function getUserData(){
if (session) {
return session.user;
}
return null;
}
On $rootScope.$on('$stateChangeStart' i have :
AuthService.loadSessionData();
Which translates to:
function loadSessionData() {
$http({
url: API.URL+'auth/session-data',
method: 'GET'
})
.success(function(response)
{
session = response;
})
.error(function(err){
console.log(err);
});
};
One of the issues here are that i have to set a timeout on AuthService.getUserData() because when this executes, the call that retrieves the session data from the server is not finished yet, but this is a bad practice.
Here is the complete service code http://pastebin.com/QpHrKJmb
How about using resolve? If I understood correctly you wish to have this data in your controller anyway.
You can add this to your state definitions:
.state('bla', {
template: '...'
controller: 'BlaCtrl',
resolve: {
user: ['AuthService', function(AuthService) {
return AuthService.loadSessionData();
}
}
}
also, alter your loadSessionData function: (make sure to inject $q to AuthService)
function loadSessionData() {
return $q(function(resolve, reject) {
$http({
url: API.URL + 'auth/session-data',
method: 'GET'
})
.success(function(response)
{
if (response) {
resolve(response);
} else {
reject();
}
})
.error(function(err){
reject(err);
});
})
}
Lastly, add the user object from the resolve function to you controller:
app.contoller('BlaCtrl', ['$scope', 'user', function($scope, user) {
$scope.user = user;
}]);
What does this accomplish?
In case the user does not have a valid session or an error occurs, the state change is rejected and the event $stateChangeError is thrown. You can listen (like you did for $stateChangeStart for that event and respond with a modal, redirect to an error page, or whatever.
You only pull the session for states that needs it - not for every state change.
The state is not resolved until the user data is resolved as well (either by resolve or reject).
You should call loadSessionData() in getUserData()
function getUserData(){
loadSessionData()
.success(function(response)
{
if (response) {
return response.user;
}
})
return null;
}
and
function loadSessionData() {
return $http.get(API.URL+'auth/session-data');
};

How to prevent state change until value is resolved

I have authentication set up in such a way that I want to prevent any route/state from loading until I know that the user is authorized to access the page. If they are, then the requested page should load, if not, then it should go to the login page.
My config function:
$stateProvider
.state('login', {
url: '/login',
templateUrl : 'login.html',
controller : 'loginController',
data: {
authorizedRoles: [USER_ROLES.guest]
}
})
.state('home', {
url: '/',
templateUrl : 'home.html',
controller : 'homeController',
data: {
authorizedRoles: [USER_ROLES.admin]
}
})
.state('admin', {
url: '/admin',
templateUrl : 'admin.html',
controller : 'adminController',
data: {
authorizedRoles: [USER_ROLES.admin]
}
});
$urlRouterProvider.otherwise('/login');
$locationProvider.html5Mode(true);
My run function:
$rootScope.$on('$stateChangeStart', function(event, next) {
event.preventDefault();
function checkAuthorization() {
if(!AuthService.isAuthorized(authRole)) {
$state.go('login');
} else {
$state.go(next.name);
}
}
if(AuthService.getRoleId() === undefined) {
// We'll have to send request to server to see if user is logged in
AuthService.checkLogin().then(function(response) {
checkAuthorization();
});
} else {
checkAuthorization();
}
})
If I keep the event.preventDefault() in my run function, then the app will be stuck in a loop always going to the requested state. If I remove the event.preventDefault() statement then the app will load the view (which will be visible for a second) before realizing the user should not be allowed to view it (and then go to the correct state).
How can I solve this problem?
You should use resolve and make request to the server to see if user is logged in the resolve
https://github.com/angular-ui/ui-router/wiki#resolve
.state('whatever',{
...
promiseObj: function($http){
// $http returns a promise for the url data
return $http({method: 'GET', url: '/someUrl'}).$promise;
},
...
}
OR
if you have make a call in the controller, make the call in resolve in state, in which your api should response with a 401 if user is not login in and redirect to the log in screen if you have an intercept service.
There is detailed explanation how to do this kind of resolve/wait stuff in this Q & A with working plunker.
An extracted version of the Auth service is:
.factory('userService', function ($timeout, $q) {
var user = undefined;
return {
// async way how to load user from Server API
getAuthObject: function () {
var deferred = $q.defer();
// later we can use this quick way -
// - once user is already loaded
if (user) {
return $q.when(user);
}
// server fake call, in action would be $http
$timeout(function () {
// server returned UN authenticated user
user = {isAuthenticated: false };
// here resolved after 500ms
deferred.resolve(user)
}, 500)
return deferred.promise;
},
// sync, quick way how to check IS authenticated...
isAuthenticated: function () {
return user !== undefined
&& user.isAuthenticated;
}
};
})
where the most important parts are
var user = undefined; - "global" variable which is
containing user and can answer if he has rights
does not contain user (yet) and the answer is "not authorized" then
returned service function: isAuthenticated
That should solve the issue. check more details here

Angular js $http factory patterns

I've a factory named as 'userService'.
.factory('userService', function($http) {
var users = [];
return {
getUsers: function(){
return $http.get("https://www.yoursite.com/users").then(function(response){
users = response;
return users;
});
},
getUser: function(index){
return users[i];
}
}
})
In the first page, On button click I want to call getUsers function and it will return the 'users' array.
I want to use 'users' array in the second page. How can I do it?
P.s: I'm using getters and setters to store the response in first page and access the same in second page. Is this the way everyone doing?
1). getUsers. For consistence sake I would still use the same service method on the second page but I would also add data caching logic:
.factory('userService', function($q, $http) {
var users;
return {
getUsers: function() {
return users ? $q.when(users) : $http.get("https://www.yoursite.com/users").then(function(response) {
users = response;
return users;
});
},
getUser: function(index){
return users[i];
}
};
});
Now on the second page usage is the same as it was on the first:
userService.getUsers().then(function(users) {
$scope.users = users;
});
but this promise will resolve immediately because users are already loaded and available.
2). getUser. Also it makes sense to turn getUser method into asynchronous as well:
getUser: function(index){
return this.getUsers().then(function(users) {
return users[i];
});
}
and use it this way in controller:
userService.getUser(123).then(function(user) {
console.log(user);
});
Here is the pattern i have followed in my own project. You can see the code below
.factory('userService', function($http) {
return {
serviceCall : function(urls, successCallBack) {
$http({
method : 'post',
url : url,
timeout : timeout
}).success(function(data, status, headers, config) {
commonDataFactory.setResponse(data);
}).error(function(data, status, headers, config) {
commonDataFactory.setResponse({"data":"undefined"});
alert("error");
});
}
},
};
After service call set the response data in common data factory so that it will be accessible throughout the app
In the above code I've used common data factory to store the response.

How can I execute some code asynchronously before methods in my service are called?

I am having some problems with executing some tasks before my service is initialised and it's methods used. Some context:
I am producing an application which uses REST to communicate with 2 different backend systems (the reason for this is that if our client upgrades in the future it will still work). These backend systems have slightly different paths for the same REST calls.
To know which calls to use I thought a solution might be to call one test endpoint which exists in one, but not the other, and depending on the response code received, set a variable which is the beginning of the URL. e.g. /rest/services/StartpointService/.
All the REST calls are in a single factory and I tried something like this:
angular.module('myApp.services', [])
.factory('myServices', [
'$http',
'$q',
function($http, $q) {
//test function, if success we are using 1 backend, if fails, we use the other
var loginTest = function() {
var deferred = $q.defer();
$http( {
method: 'POST',
url: '/um/login?um_no_redirect=true'
})
.success(function(data, status, headers, config) {
deferred.resolve(status);
})
.error(function(data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
};
var url;
loginTest()
.then( function(response) { //if backend1
if(responseCode === 200) {
url = '/rest/services/etc/etc' //set the URL
}
},
function(errorCode) { //If backend2
if(errorCode === 404) {
url = '/LCConnector/rest/services/etc/etc';
}
});
var service = {
realCall : function() {
//use 'url' variable in the $http call
}
}
return service;
}]);
Obviously as the loginTest is asyncronous, the service is injected into my controller and is called before url is set.
I have looked into running in a config or run block when the app is first initialised but can't quite understand how to get the variable out.
If i can give anything further details, please let me know!
Regards,
Augier
If this check is required before the application is initialized you can manually bootstrap your application after the Ajax call. Inside of your fail() or done() call backs you can alter the module config to reflect the url you need. From there you can easily inject your config into any service that requires this url.
example on jsfiddle
<div ng-controller="MyCtrl">{{url}}</div>
//if you chanée this url to /echo/fail and url will now be url1
var urlToCheck = '/echo/json/';
var myApp = angular.module('myApp', []);
myApp.controller("MyCtrl", ["$scope", "config", function ($scope, config) {
$scope.url = config.url;
}]);
$.ajax({
url: urlToCheck
}).fail(function () {
myApp.constant('config', {
url: '/fail-url'
});
}).done(function () {
myApp.constant('config', {
url: '/done-url'
});
}).always(function () {
angular.bootstrap(document, ['myApp']);
});
You could take advantage of $routeProvider, which allows you to delay your controller instantiation until your promise has been resolved.
$routeProvider exposes a method called resolve for that purpose. See the AngularJS doc:
http://docs.angularjs.org/api/ngRoute.$routeProvider
Additional information in this excellent SO question:
AngularJS : Initialize service with asynchronous data
Highly recommended.

Resources