2
In an application made with Angularjs, some pages are protected by login.
I configured the module as follows:
var app = angular.module('App', ['ngRoute', 'ngTouch', 'mobile-angular-ui']);
app.config(['$routeProvider','$locationProvider', function ($routeProvider, $locationProvider) {
$routeProvider.
//...
.when('/dashboard', {
title: 'Dashboard',
templateUrl: 'view/dashboard.html',
controller: 'authCtrl',
requireLogin: true
})
//...
$locationProvider.html5Mode(true);
}])
.run(function ($rootScope, $route, $location, Data, Session) {
$rootScope.$on('$locationChangeStart', function (event) {
var nextPath = $location.path();
var nextRoute = $route.routes[nextPath];
if (nextRoute.requireLogin && !Session.getUserAuthenticated()) {
$location.path("/login");
}
});
});
Note that at the end of the above code, I have a service (Session.getUserAuthenticated()) that checks if the user logged in before changing the route, see the code:
app.service('Session', function($http) {
this.getUserAuthenticated = function() {
var auth = false;
$http.post('api/v1/session').then(function (results) {
if(results.data.uid) auth = true;
});
return auth;
};
});
The problem is that the above service always returns false, since it does Return before the $http.post response, how do I fix the problem? It is possible to wait for the POST response or the logic I am using is incorrect?
Pass a callback to the service. But the most recommended I believe is not to send the parts that should only be accessed when authenticated.
– Vinícius Gobbo A. de Oliveira
In fact you are returning auth false because it is returned before the POST occurs. The post is asynchronous. In this case you must work with Callback or Promisses to only return if it is authorized within the POST result
– Caputo
@Caputo how would that be? Would you have to remove that service or change it? Thank you.
– Filipe Moraes
@Viníciusgobboa.de Live these blocking is only in frontend, on the server I also do the checking, this would only be to avoid unnecessary requests. But how would it be recommended? Thanks.
– Filipe Moraes
I’m a little busy here, I don’t know how your English is, but take a look at this answer and its link http://stackoverflow.com/a/16627409/3590714
– Caputo