Rorschach120 Rorschach120 - 7 months ago 43
Javascript Question

angular $locationChangeStart not getting called properly, what do?

I'm working on a MEAN app that is based upon Brian Ford's angular-express-blog app on GitHub.

The problem I'm having is that I need to be able to call my UserService service on $locationChangeStart in order to check if there is a user logged. Most of the examples I see have you setting

$rootScope.$on('$locationChangeStart'...
in the module declaration. This doesn't allow me to access my custom service so my solution was to put it in a controller and call it in my main layout file.

I've set it up like so but the app does nothing. It doesn't even call an error. Can any of you spot the problem with this code?

Here is my github repo.

LayoutCtrl.js:

angular.module('myApp').
controller('LayoutCtrl', function($scope, $http, UserService) {
$scope.$on( "$locationChangeStart", function(event, next, current) {
if ( UserService.getUser() === null ) {
// no logged user, we should be going to #login
if ( next.templateUrl == "partials/login.html" ) {
// already going to #login, no redirect needed
} else {
// not going to #login, we should redirect now
$location.path( "/login" );
}
}
});
});


Layout.jade:

doctype html
html(ng-app="myApp", ng-controller='LayoutCtrl')
head
meta(charset='utf8')
base(href='/')
title Angular Express Seed App
link(rel='stylesheet', href='/css/app.css')
body
block body


And UserService.js:

angular.module('myApp').
service('UserService', function(){
var $scope = this;
var user = null;
$scope.user = {};

$scope.setUser = function(data){
user = data;
};
$scope.getUser = function(){
$scope.user = user;
};

return $scope;
});

Answer

I don't understand how your service is supposed to work, your getUser function returns nothing (undefined).

Use this instead:

angular.module('myApp').
    service('UserService', function(){
        var user;

        this.setUser = function(data){
          user = data;
        };
        this.getUser = function(){
          return user;
        };
  });

so your problem is that undefiend !== null

and you are checking for this:

 if ( UserService.getUser() === null )

if you want to check if it's undefined (or other falsy values) use this:

 if ( ! UserService.getUser() )

also you should inject $location:

 controller('LayoutCtrl', function($scope, UserService, $location) {

Debugging

  • use console.log to check the flow of your application
  • console.log(UserService.getUser()) # undefined

alternative solution with a run block :

angular.module('myApp').
    run(function($rootScope, UserService, $location) {
        $rootScope.$on( "$locationChangeStart", function(event, next, current) {

        });
    });