The functionality of the .state property is not performing as anticipated

I am trying to implement a check before entering a state using the ui-router resolve property. The goal is to verify if the user is logged in by calling the AuthService function. However, I am not getting any result.

  • Angular version: 1.5.8
  • angular-ui.router version: 0.2.18

index.route.js

angular.module('app').config(routerConfig);

/** @ngInject */
function routerConfig($stateProvider, $urlRouterProvider, USER_ROLES) {
    $stateProvider
    .state('dashboard', {
        url: "/dashboard",
        templateUrl: "app/views/dashboard_2.html",
        data: { requiresAuth: true, pageTitle: 'Dashboard', authorizedRoles: ['admin'] } ,
        resolve: {
          isLoggedin: ['AuthService', function(AuthService) {
              return AuthService.isAuthenticated();
          }]
        }
      })
});

auth.service.js

'use strict';
angular
.module('app')
.factory('AuthService', function($log, $http, $q, $cookies){
    var authService = {};
    // .. login and logout methods...
    authService.isAuthenticated = function () {
      return !!$cookies.getObject('currentUser');
    };

    return authService;
});

index.run.js

angular
    .module('app')
    .run(function($rootScope, $state, $log, AuthService, AUTH_EVENTS) {
 $rootScope.$on('$stateChangeStart', function (event, to, toParams, from, fromParams) {
                // $log.debug('state change starts');
                $log.debug(to.resolve);
            });

I have come across information stating that resolve returns a promise object, but my simple function only returns true/false. Could this be the issue? Any suggestions on how to properly handle this situation?

Answer №1

If you want the resolve function to work with a promise, ensure that you return a promise in your code. Adjust your code as follows:

isLoggedin: ['AuthService', '$q', function(AuthService, $q) {
    var defer = $q.defer();
    var isLoggedIn = AuthService.isAuthenticated();

    if (isLoggedIn) {
       defer.resolve();
    } else {
       defer.reject();
    }

    return defer.promise;
}]

Alternatively, you can eliminate the resolve keyword from your state configuration and update your run block like this:

angular
        .module('app')
        .run(function ($rootScope, $state, $log, AuthService, AUTH_EVENTS) {
            $rootScope.$on('$stateChangeStart', function (event, toState, toParams, from, fromParams) {
                if (toState.name === 'dashboard') {
                    if (!AuthService.isAuthenticated()) {
                        // Prevent navigating to state
                        e.preventDefault();
                        // Redirect to another page like login
                        //$state.go('login')
                        return;
                    }
                }
            });
        });

Edit

You can make the above code (2nd approach) more generic by doing this:

angular
        .module('app')
        .run(function ($rootScope, $state, $log, AuthService, AUTH_EVENTS) {
            $rootScope.$on('$stateChangeStart', function (event, toState, toParams, from, fromParams) {
                if (toState.requireAuthenticationFoo && !AuthService.isAuthenticated()) {
                    // Prevent navigating to state
                    e.preventDefault();
                    // Redirect to another page like login
                    //$state.go('login')
                    return;
                }
            });
        });

Now include the key requireAuthenticationFoo in your state configuration:

state('dashboard', {
    url: "/dashboard",
    templateUrl: "app/views/dashboard_2.html",
    data: {requiresAuth: true, pageTitle: 'Dashboard', authorizedRoles: ['admin']},
    requireAuthenticationFoo: true
})

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

Having trouble pinpointing the source files that are loading .js in the <head> section of my Magento website

My console is showing me three 404 errors related to missing .js files in the head section of my website. Even though I don't actually need these files, I want to stop receiving the 404 errors as they are affecting my analytics and SEO. The files caus ...

Utilizing the POST request to signal the server's response of a 404

I'm having trouble sending a POST request to my server in order to update a user's information. Even though I have verified that the URL is correct, I keep receiving a 404 error response. GET requests are working fine, but there seems to be an is ...

Is it possible for the ".filter" function to verify if the target contains multiple attributes?

I'm currently working on a checkbox filter setup and using Jquery's .filter to sort through some divs. Below is the snippet of Jquery code that I am using: $(document).ready(function(){ var checkboxes = $('div.filter-groups').find(&ap ...

javascript search for parent function argument

I am struggling to figure out how to locate the key in my json array. When I try to find the key using a function parameter, it does not seem to work. This is a snippet of my json data: ... { "product": [ { "title": " ...

Discovering the change in checkboxes resulting from a user click or JavaScript code can be accomplished by utilizing the document.getElementById

Here is a JavaScript function designed to select all checkboxes with a specific ID function checkall(type) { var total_number = document.getElementById('total_number').value; if (type == 1) { for (i = 1; i <= total_number; i++ ...

Maintain the value of `this` using a recursive setImmediate() function

Hey there! I'm working on a node.js app where I need to utilize setImmediate() to recursively call a function while maintaining its context for the next iteration. Let's take a look at an example: var i=3; function myFunc(){ console.log(i ...

when the submit button is clicked, verify whether the input field is empty

I have exhausted all my options and nothing seems to work. All I want is for the following functionality to be implemented: When a submit button is clicked -> check if a text field is empty -> if it is, display an error alert and prevent advancing t ...

Unveiling the secrets of the Google Region Lookup API

I am struggling to incorporate the Region Area Lookup feature from Google Maps into my project. Despite it being an experimental feature, I am having difficulty getting it to function correctly. Initially, I attempted to integrate this feature into a Reac ...

The Mongoose server unexpectedly shut down

We encountered a server issue while working on our movie database project. After deleting and rewriting the code, we ran into a problem. Here is the advice given by our instructor: Troubleshooting mongoose.connect errors If you are facing a connection ...

The Ajax call retrieving the complete script

For the past few days, I've been trying to find a solution to my issue. Essentially, I have two files: index.html and hellonode.js. Index.html contains a div with text and a button that should initiate a request to hellonode.js when clicked. The purpo ...

Using JavaScript modules in a multi-page website with Closure Compiler integration

I have developed a web application that consists of multiple pages along with some JavaScript files containing shared code. - common1.js - common2.js - page1.js - page2.js - page3.js ... The shared files are being loaded with page1 and, upon a button clic ...

Typescript throwing a fit over a lack of index signature in explicit type declaration

When working with Typescript, I encountered an error message stating that "Element implicitly has an 'any' type because type 'HumansToDogs' has no index signature." Despite my code appearing explicit and straightforward, I am struggling ...

Is there a way to replace jQuery's .submit() method with Angular?

Is there a way to trigger an Angular event similar to the jQuery method shown below? $('.link').click(function () { $('form').submit(); // this will submit form }); It's important to clarify that this is not using the onSubm ...

The most effective method for calculating overhead is through the utilization of synchronous techniques

I'm currently developing a nodeJS app that heavily relies on synchronous methods, particularly for file operations and spawning child processes. I am looking to assess the impact of these blocking main thread activities in terms of overhead. What woul ...

Converting JSON Data into a Formatted HTML Table

I've been working on this for a few days now and still haven't figured it out. So far, I've created a PHP script that displays my JSON data structure. Now, I'm attempting to create an HTML script that will display the results in JSON fo ...

Is there a method in Vuejs to choose a tab and update components simultaneously?

Currently facing an issue where selecting a tab does not refresh the input field in another component, causing data persistence. The data is stored in vuex, so I'm looking for a solution to refresh the component for usability. Appreciate any assistanc ...

When the input element's visibility is toggled, the text elements wiggle slightly

I have created a layout that looks like this: <ul id="playlists" class="ui-sortable"> <li data-id="b69c8348-f47c-4156-a975-a2f1009610a8" data-type="3" class="listItem playlist active"><i class="fa fa-list fa-fw"></i> &l ...

add text nodes with unnecessary quotation marks around my selection list

Looking to incorporate a select list into my website using a button. I must utilize nodes for access within the DOM to retrieve its value later, so innerHTML isn't an option. Experiencing difficulty as createTextNode seems to encase my list in quota ...

Dividing the body of md-tabs in Angular material

My current project involves using angular material (https://material.angularjs.org/) I'm curious if there is a method to separate a tabs body from the tab list in angular material. Unfortunately, I couldn't find any information regarding this in ...

Leveraging Cordova Plugins in Ionic 2

I've spent a considerable amount of time searching on Google, but I haven't been able to find a clear answer. How exactly does the syntax for calling Cordova plugins in Ionic 2 work? For example, in Ionic 1: When using a Facebook plugin, I would ...