AngularJS encountered an error: undefined is not an object when evaluating 'a.$current.locals[l]'

In my Angular project setup, I have a functionality where if a user visits /cloud without being logged in (resulting in a failure of the isLoggedIn() check), they are redirected to /login. Conversely, if a logged-in user tries to access /login, they get redirected back to /cloud.

However, upon clicking the logout button to clear local storage, I encounter the following error message (although everything continues to function normally):

Error: null is not an object (evaluating 'a.$current.locals[l]')

My logs indicate that this issue occurs within the onEnter method of the logout controller.

Having limited experience with Angular, any advice or guidance on resolving this would be greatly appreciated.

var routerApp = angular.module('myapp', ['ui.router'])
    //config for state changes
    .factory('Auth', function($http, $state, $q) {

        var factory = { isLoggedIn: isLoggedIn };
        return factory;

        function isLoggedIn(token) {
            return $http.post('/auth/session', {token:token});
        }

    })
    .config(function($stateProvider, $urlRouterProvider, $locationProvider) {

        $locationProvider.html5Mode(true);
        $urlRouterProvider.otherwise('/cloud');

        var authenticated = ['$q', 'Auth', '$rootScope', function ($q, Auth, $rootScope) { 
            var deferred = $q.defer();
            if (typeof window.localStorage['authtoken'] === 'undefined') {
                var authtoken = undefined;
            } else {
                var authtoken = window.localStorage['authtoken'];
            }
            Auth.isLoggedIn(authtoken).then(function() {
                deferred.resolve();
            }, function() {
                deferred.reject();
            });
            return deferred.promise;
        }];

        var authGuest = ['$q', 'Auth', '$rootScope', function ($q, Auth, $rootScope) { 
            var deferred = $q.defer();
            if (typeof window.localStorage['authtoken'] === 'undefined') {
                var authtoken = undefined;
            } else {
                var authtoken = window.localStorage['authtoken'];
            }
            Auth.isLoggedIn(authtoken).then(function() {
                deferred.reject();
            }, function() {
                deferred.resolve();
            });
            return deferred.promise;
        }];

        $stateProvider

            .state('login', {
                url: '/login',
                templateUrl: 'pages/templates/login.html',
                resolve: { authenticated: authGuest }
            })

            .state('logout', { url: '/logout', onEnter: function($state) { localStorage.clear(); $state.go('login'); } })

            .state('cloud', {
                url: '/cloud',
                templateUrl: 'pages/templates/cloud.html',
                resolve: { authenticated: authenticated }
            })

    })
    .run(function ($rootScope, $state) {
        $rootScope.$on('$stateChangeError', function (event, from, error) {
            if(from.name == "login") {
                $state.go('cloud');
            } else {
                $state.go('login');
            }
        });
    });

Answer №1

Identifying the issue:

    var authenticated = ['$q', 'Auth', '$rootScope', function ($q, Auth, $rootScope) { 
        var deferred = $q.defer();
        if (typeof window.localStorage['authtoken'] === 'undefined') {
            var authtoken = undefined;
        } else {
            var authtoken = window.localStorage['authtoken'];
        }
        Auth.isLoggedIn(authtoken).then(function() {
            deferred.resolve();
        }, function() {
            deferred.reject();
        });
        return deferred.promise;
    }];

This particular function runs only once during Configuration. The promise will consistently resolve to the same value even if the LocalStorage changes. Each time you

resolve: { authenticated: authenticated }

At Configuration, you will always receive the same authenticated value.

To improve this, introduce a controller to define functions for requesting status based on different criteria.

  .controller('AuthenticationController', function($scope, '$q', Auth, '$rootScope') {
        $scope.authenticated = function () { 
            var deferred = $q.defer();
            if (typeof window.localStorage['authtoken'] === 'undefined') {
                var authtoken = undefined;
            } else {
                var authtoken = window.localStorage['authtoken'];
            }
            Auth.isLoggedIn(authtoken).then(function() {
                deferred.resolve();
            }, function() {
                deferred.reject();
            });
            return deferred.promise;
        };

        $scope.authGuest = function ($scope, '$q', Auth, '$rootScope') { 
            ....
            return deferred.promise;
        };

    });

Then, in your routing configurations:

        .state('login', {
            url: '/login',
            templateUrl: 'pages/templates/login.html',
            controller: 'AuthenticationController'
            resolve: { authenticated: $scope.authGuest() }
        })
        .state('cloud', {
            url: '/cloud',
            templateUrl: 'pages/templates/cloud.html',
            resolve: { authenticated: $scope.authenticated()}
        })

With these changes, each resolution will result in a fresh promise being created.

Disclaimer: This code is presented as a demonstration without a functional implementation. It serves as pseudo-code to guide in the right direction.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Preserve all the impact of a website indefinitely

Imagine a scenario where a webpage contains a button that, when pressed, creates another button below it. How can you save this effect so that when you reopen the webpage, the new button is still displayed below the original one? Is there a way to store ...

the speed of accessing an array in JavaScript

Assuming there is a javascript array1 with 10,000 elements, what would be the time complexity of: var array2=new array(); array2.push(array1); and what about the time complexity of var object={}; object['array2']=array1; Are both operatio ...

Tips for assigning an ID to a span element within a for loop

I am facing a challenge where I need to assign IDs to span tags that do not have the id attribute. These IDs need to be assigned sequentially by incrementing through a for loop and passing my geneologicalSequenceNumber into each span tag. Can you guide me ...

Is there a way to make a text area move along with the mouse cursor?

I have been working on my first website and everything is running smoothly so far. However, I have a new idea that I am struggling to implement. Some of the pages on my site feature a video player with buttons to select different videos. When a viewer hove ...

The gltf model fails to load on Chrome for Android when using Threejs

I encountered an issue while attempting to showcase a basic GLTF 3d model on my website. Surprisingly, it functions smoothly on desktop Mac and Windows, as well as on iOS in Safari and Firefox. However, it fails to load on Android's Chrome browser. St ...

Guidelines for breaking down a produced string within the console.log statement in JavaScript

Seeking clarification on this inquiry. I am a complete novice when it comes to coding. Currently, I have implemented the following do while loop code taken from w3s: var text = ""; var i = 1; do { text += "The number is " + i; i++; ...

"Enhance your JavaScript skills with the power of jQuery

I am currently facing an issue where I need to retrieve the value of the normaltagCmt element: <div id="random no"> <div id="normaltagdialog"> <table style="width:100%; height:100%" border="2px"> <tr style="width:100%; height: ...

Identifying Angular 2 templates post-file separation: a step-by-step guide

I am currently trying to figure out how to initiate a project in Angular 2 and have encountered an issue. Following the steps outlined in this Angular 2 guide, I was able to separate my .ts files from .js files by configuring my 'temp' directory ...

Trouble with reading from a newly generated file in a node.js program

Whenever I launch my results.html page, I generate a new JSON file and use express.static to allow access to the public folder files in the browser. Although my application is functioning properly, I find myself having to click the button multiple times f ...

Show concealed elements above everything else

I've encountered an issue with my custom dropdown list as it displaces other elements when it appears. I want it to overlay on top of everything else, similar to the default select behavior. Despite trying to set position: relative; and z-index:100;, ...

Dealing with unanticipated consequences in computed attributes - Vue.js

I am facing a challenge while working on the code below. I am attempting to utilize the getTranslation object to match values from the originalKeys array and then add these values to a new array called allKeys. However, ESLint has flagged an error stating ...

Make the table in a bootstrap design appear with a border when you hover over a cell using the table

Looking for a solution to make the border work as expected when hovering over each td in a table like this example: https://jsfiddle.net/nmw82od1/ Here is the CSS code: .table1 td:hover { border: 1px solid black; } .table2 td:hover { border: 1px do ...

Having trouble interacting with Bootstrap modal dialog when fullPage.js is active

Whenever I attempt to click on the button, a Bootstrap modal dialog box appears but remains unresponsive no matter what I try. My project utilizes both Bootstrap and fullPage.js http://codepen.io/anon/pen/obEOzO <body> <div id="fullpage"> &l ...

The problem of Angular material toolbar's erratic height issue

Currently, I am using angular material version 1.1.0-RC.5 which involves a simple toolbar creation. <md-toolbar> </md-toolbar> However, there seems to be an issue when the browser width is less than 960px - the toolbar's height changes t ...

The second AJAX call is unsuccessful

I have created a dynamic ajax website that retrieves pages from the /pages folder and displays them within an ajax-container div on my index.php. Now, I am looking to implement a second ajax request that will only be triggered on certain pages. For examp ...

Encountering a mixed content error in Internet Explorer 8 due to the Nivo slider jQuery?

I am encountering an issue with the Nivo jQuery slider on my HTTPS website, as it appears to be generating a mixed content error in Internet Explorer 8. Despite posting on the Dev7 Studios forum and conducting extensive research on the IE 8 mixed content ...

Storing a Vue JS component as a string in a variable and displaying it using that variable

I am currently working on a project where I need to implement the following code snippet: <template v-for="(element, k) in place.data.content"> <data_elements[element.name].component></data_elements[element.name].component> </te ...

I am experiencing difficulty accessing Laravel and AngularJS on my local host from another computer within my network

I currently have a project running smoothly on my main machine using the command php -S localhost:8080 -t public to start a local server. Everything is functioning perfectly in this setup. However, I am now attempting to access the project from another c ...

Enhancing webpage design by dynamically changing borders and headers using JavaScript

I have implemented a fixed positioning for the table headers using the following code: onScroll={() => { document.querySelector('thead').style.transform = `translate(0,${this.scrollRef.scrollTop}px)`; }} However, when I scroll the ta ...

React functional components can utilize switch cases for conditional logic

I am attempting to create a multi-step form using a switch case, but for some reason, changing the state with nextPrev does not update the case. export const FormSteps = ({items, pending}) => { const [step, setStep] = useState (2) const nextS ...