"Using AngularJs, discover the best method for redirecting to a specific state based on a flag

When the userAccess flag in the controller is false, I want to hide all application content from the user and redirect them to access.html which includes a required access form. However, when using the code below, an error transition superseded is thrown. Any suggestions on how to accomplish this task using angularjs ui.router ?

mainCtrl.js


$scope.cookie = $cookies.get('jklHr');
var parts = $scope.cookie.split("|");
var uidParts = parts[7].split(",");
$scope.newUser._id = uidParts[0];
var userAccess = AuthService.getCurrentUser($scope.newUser._id);

if(!userAccess) {
    console.log("Access Denied");
    $state.go('app.access');
} 

app.js


angular.module('App', [
    'ui.router',
    'ui.bootstrap',
    'ui.bootstrap.pagination',
    'ngSanitize',
    'timer',
    'toastr',
    'ngCookies',
]).config(function($stateProvider, $httpProvider, $urlRouterProvider) {
    'use strict'

    $urlRouterProvider.otherwise(function($injector) {
        var $state = $injector.get('$state');
        $state.go('app.home');
    });

    $stateProvider
        .state('app', {
            abstract: true,
            url: '',
            templateUrl: 'web/global/main.html',
            controller: 'MainCtrl'
        })
        .state('app.home', {
            url: '/',
            templateUrl: 'view/home.html',
            controller: 'MainCtrl'
        })
        .state('app.dit', {
            url: '/dit',
            templateUrl: 'view/partials/logs.html',
            controller: 'LogsCtrl',
            resolve: {
                changeStateData: function(LogsFactory) {
                    var env = 'dit';
                    return LogsFactory.resolveData(env)
                        .then(function(response) {
                            return response.data
                        });
                }
            }
        })
        .state('app.access', {
            url: '/access',
            templateUrl: 'view/partials/access.html',
            controller: 'AccessCtrl'
        });
});

Answer №1

To enhance security, set up an interceptor that will handle all HTTP requests. In the event that the "resolve" function returns a status code of 401, you can redirect users to the login page, or if it returns 403, show them the forbidden view.

Learn more about AngularJS's $http service at https://docs.angularjs.org/api/ng/service/

Answer №2

The issue at hand is attempting to modify a state while another state modification is still ongoing. The user interface router has event handlers for when a state transition begins and concludes.

$rootScope.$on("$stateChangeStart",  function(event, toState, toParams, fromState, fromParams) {

});

Therefore, it would be wise to include your redirect logic within this event handler. Additionally, I advise relocating the user validation process to a higher level in your application, such as within .run(), with certain exceptions made for login states. This approach will eliminate the need to validate users in every individual controller.

Answer №3

Ensure that you have the latest version of AngularJS and angular-ui installed. If you are using an older version, make sure to verify the compatibility of angular-ui with your current angular version. https://github.com/angular-ui/ui-router/issues/3246 If this does not resolve the issue, include the following line in your app.config:

$qProvider.errorOnUnhandledRejections(false)

Remember to also add the dependency $qProvider in your config function.

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

Obtain the leaf nodes from a combination of arrays and objects using Lodash

Here is the code structure I want to share with you before explaining my requirements. It displays the input array layout along with the desired outcome: [ { link: "someurl", name: "Foo", subCats: [ { link: "anotherurl", ...

How can I handle JSON data that contains undefined values?

Similar Question: Is it possible to parse JSON with special 'undefined' values using JavaScript? I'm curious if there's a way to parse something like javascript JSON.parse('{ "name": undefined}'); that is generated by an API ...

Vue Bootstrap Checkbox and <b-table> with <b-form-checkbox> components combine to provide a powerful and flexible user

I am currently implementing b-form-checkbox with b-table to fetch the selected module Ids. <b-table id="module-table" :items="list.modules" :fields="fields" :busy="isBusy"> <template slo ...

Monitor the input value for any changes in Angular 8 using the listen component

Hey there! I'm currently working with a component that includes the input @Input() userId: number[] = []; to receive a list of user IDs. Specifically, I have integrated this component into another one, such as the news component: <kt-user-post-li ...

Setting limits on relational data in Nest.js involves utilizing the appropriate decorators and methods to restrict

In my Nest.js application, I am working with relational data and using the TypeOrm query builder to retrieve the data. Here is an example of how I am querying the data: async find() { return this.landingSectionNameRepository.createQueryBuilder(&apo ...

Retrieve the property of an object from within an array

I am dealing with an array structure like this: const arr = [{ name: 'One', id: 1 }, { name: 'Two', id: 2 } ]; My goal is to extract and return the name of the object if its id matches a certain value. After exp ...

Deleting a document by ObjectID in MongoDB with Node and Express without using Mongoose: A step-by-step guide

As a newcomer to backend development, I am currently using Node/Express/MongoDB with an EJS template for the frontend. I am in the process of creating a simple todo list app to practice CRUD operations without relying on Mongoose but solely native MongoDB. ...

Adjust the size of a Div/Element in real-time using a randomly calculated number

Currently, I am working on a script that is designed to change the dimensions of a div element when a button on the page is clicked. The JavaScript function connected to this button should generate a random number between 1 and 1000, setting it as both the ...

Using LIKE in MSSQL with an input parameter: A guide for Node developers

I found myself in a predicament where I was unsure how to phrase my question and where a solution seemed elusive. My current tool of choice is the mssql NPM package, but unfortunately, the documentation is not providing the necessary guidance. The goal I ...

The animation came to a halt after a brief period

Here is the code I wrote. When the button is clicked, the 3 containers should start flashing indefinitely, but they stop after a while. I can't figure out why. Any ideas? <!DOCTYPE html> <html> <head> <title></title> & ...

Is it considered beneficial to use Observable as a static class member?

Lately, I have been diving into a new Angular project and noticed that the common way to share state between unrelated components is by using rxjs Subject/BehaviorSubject as static members within the class. For instance: export class AbcService { privat ...

Pressing a button to input a decimal in a calculator

I am encountering an issue with inputting decimals in my JavaScript. I have a function that checks if the output is Not a Number (NaN). If it is, I want it to output a decimal instead. I attempted to add another conditional statement like this: var opera ...

Failure to Trigger Error Callback in Ajax Requests

I am encountering an issue with the error callback not being called when I pass the error function as an object parameter in a function. Strangely, when I define it directly within the ajax code, it works without any problems. var options = new Object(); ...

Implement the useEffect() function to handle the loading of external JavaScript on the client-side, replicating the

I have encountered a challenge while trying to integrate a rich text editor into my NextJS project. Since there are no available React components for this specific editor and it operates solely on the client side, I am required to load the necessary JavaSc ...

The accuracy of the fromPointToLatLng function in Google Map's JS API seems to be inconsistent with the actual events

My objective is to enhance user experience with a drawing tool on the map interface. I aim for a functionality where, upon single-clicking somewhere on the map using tools like the rectangle tool, the map automatically centers on that clicked location. Thi ...

Tips for avoiding the influence of the parent div's opacity on child divs within a Primeng Carousel

I'm struggling to find a solution to stop the "opacity" effect of the parent container from affecting the child containers. In my code, I want the opacity not to impact the buttons within the elements. I have tried using "radial-gradient" for multipl ...

After a page reload, Material-UI stops functioning properly

I am currently working with Material UI in a Next.js project. When I run npm run dev, everything looks good. However, whenever I refresh the page, all the styling breaks. Has anyone experienced this issue before? It seems like Material-UI is no longer func ...

Looking to spice up your static HTML site? Dive into the world of Ruby on

I recently developed an app that features a static HTML webpage containing text and images, and now I'm interested in incorporating Ruby on Rails to explore its capabilities further. After creating a basic RoR application, I copied the HTML content f ...

Issue with EnumDeserializer in jackson-mapper 1.9.12 version

I'm currently working on a scenario where I need to map a String to an enum Object using the Jackson ObjectMapper.readValue(String,Class) API. The issue arises when my JSON string contains a Task Object with an Action enum defined as follows: public ...

Transmit information between Asp.net Core and Asp.net Mvc using AngularJS

I am currently working on two different projects, one using Asp.net Core and the other using Asp.net Mvc. I need to transfer data from the first project (Asp.net Core) to the second project (Asp.net Mvc) using AngularJS. However, I am facing an issue when ...