Go to a specific state based on conditions using Angular's UI-Router

Our main app currently offers a 'Portfolio' tool in beta testing. Users who have access to the beta can easily navigate to the Portfolio tool without needing an additional login upon logging into the main app. For those who do not have beta access, they will be directed to a Portfolio login page (referred to as portfolio.login) where they can log in or reach out to support/sales for assistance. At the moment, I have included a check in the resolve block, however, while $state.go('portfolio.login') seems to fetch the correct partials, it does not render them on the screen or take the user to the appropriate URL.

Code:

angular.module('portfolio.manager').config(function ($logProvider, $stateProvider) {
'use strict';

    $stateProvider
    .state('portfolio.manager', {
        url: '/manager',
        resolve: {
            CheckLoggedIn: function ($state, loggedIn) {
                var _loggedIn = loggedIn.checkUser();
                if (!_loggedIn) {
                    $state.go('portfolio.login');
                    console.log('not authorized');
                }
            },
            portfolioAuthService: 'portfolioAuthService',

            User: function(portfolioAuthService){
              return portfolioAuthService.getUser();

            },
            Portfolios: function (User, portfolioManagerService) {
                return portfolioManagerService.getPortfolios();
            }
        },
        views: {
            'main@': {
                templateUrl: 'app/portfolio/manager/portfolio-manager.html',
                controller: 'PortfolioManagerCtrl'
            },
            '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="94fafbb9e4fbe6e0f2fbf8fdfbe7d4e4fbe6e0f2fbf8fdfbbaf9f5faf5f3f1e6">[email protected]</a>': {
                templateUrl: 'app/portfolio/manager/partials/no-portfolios.html'
            },
            '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aecddccbcfdacbeedec1dcdac8c1c2c7c180c3cfc0cfc9cbdc">[email protected]</a>': {
                templateUrl: 'app/portfolio/manager/partials/create.html'
            }
        }
    })

Answer №1

A few days back, I encountered a similar issue. Instead of utilizing resolve, my approach involved checking the user's authentication status whenever the state changes. This was achieved by defining the run module and listening for the $stateChangeStart event. Upon triggering this event, an examination was conducted to determine if the current state necessitated authentication. Subsequently, verification of the user's logged-in status was performed.

angular.module('portfolio.manager').config(function ($logProvider, $stateProvider) {
'use strict';

    $stateProvider
    .state('portfolio.manager', {
        url: '/manager',
        resolve: {
            portfolioAuthService: 'portfolioAuthService',

            User: function(portfolioAuthService){
              return portfolioAuthService.getUser();

            },
            Portfolios: function (User, portfolioManagerService) {
                return portfolioManagerService.getPortfolios();
            }
        },
        data: {
            requiredAuthentication: true
        },
        views: {
            'main@': {
                templateUrl: 'app/portfolio/manager/portfolio-manager.html',
                controller: 'PortfolioManagerCtrl'
            },
            '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6806074518071a1c0e070401071b2818071a1c0e0704010746050906090f0d1a">[email protected]</a>': {
                templateUrl: 'app/portfolio/manager/partials/no-portfolios.html'
            },
            '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="97f4e5f2f6e3f2d7e7f8e5e3f1f8fbfef8b9faf6f9f6f0f2e5">[email protected]</a>': {
                templateUrl: 'app/portfolio/manager/partials/create.html'
            }
        }
    })

})
.run(run);

  run.$inject = ['$rootScope','$state','loggedIn'];

  function run($rootScope,$state,loggedIn){

    $rootScope.$on('$stateChangeStart',function(e,toState){

      if ( !(toState.data) ) return;
      if ( !(toState.data.requiredAuthentication) ) return;

      var _requiredAuthentication = toState.data.requiredAuthentication;


      if (_requiredAuthentication && !loggedIn.checkUser() ){

        e.preventDefault();
        $state.go('portfolio.login', { notify: false });
        console.log('not authorized');
      }
      return;


    });
  };

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

Unable to resolve the "Error: posts.map is not a function" issue

I am currently developing a social media-like web application. One of the features I'm working on is to display all posts made by users. However, when I run my code, it doesn't show anything and I get an error in the console that says "Uncaught T ...

Is there a way for me to track the actions of AngularJS when I interact with a link?

Within my application, there is a basic link that directs to an absolute page with its target set to blank. However, when I click on this link, the new page opens in a new window but my application screen goes blank. I am currently using Angular and tryi ...

Personalized VueJS Counter

Just started learning VueJS and I've encountered a challenge while attempting to build a custom counter. Here is the code snippet: <template v-for="(ben, i) in plan.beneficios"> <div class="w-80 w-90-480 m-auto pa-hor-5-480" :class= ...

PHP function json_encode() is causing an issue by returning an "Undefined" value

I'm working on a PHP project where I am creating an array and using json_encode() to convert it into JSON before retrieving it with $.getJSON. However, I am encountering an issue where it returns Undefined when trying to send all the data at once. Int ...

Creating a JSFiddle with sprites using source and image files from Github with THREE.JS - a step-by-step guide

Greetings! I am currently working on creating a JSFiddle based on the official THREE.js HUD Sprites example. However, I am facing an issue where the sprite images do not seem to load or apply using the URLs specified in the original file:- //... URL' ...

Error: Unable to access the 'jquery' property because it is undefined

I encountered this error while checking the Chrome console: TypeError: Cannot read property 'jquery' of undefined This is my JavaScript function: <script type="text/javascript"> var formApp = angular.module('formApp',[]); ...

Why are JavaScript errors constantly popping up when I use Django Pipeline?

After configuring Django Pipeline (version 1.3.15) for a specific group of JS files, I ensured they were in the correct order based on their appearance on my page. The collectstatic process went smoothly and when viewing the source, it looked like all th ...

Unable to administer AuthenticationController

I am attempting to inject a controller into my app.run function, but I keep encountering the following error: Uncaught Error: [$injector:unpr] http://errors.angularjs.org/1.2.10/$injector/unpr?p0=AuthenticationControllerProvider%20%3C-%20AuthenticationCon ...

Enhance Your AngularJS Routing Experience with Parameter Changes

Is there a route that opens a view with the URL /route/param1_value1/param2_value2? If, in the view, you need to redirect on button click to /route/param1_value3/param2_value2, how can you obtain the new URL from the current one? Here is an example: $ro ...

Utilizing a smooth carousel with an equal number of slides for display

I have a slick slider set to Center Mode with an even number of slidesToShow. The goal is to have the active slides at full opacity (1) and inactive slides at half opacity (0.5). However, due to the even number of slides, the implementation is not working ...

The combination of curly brackets and displaying items in a list

What is the reason behind React's failure to render the list items when the arrow function objectList contains curly braces? export default function StatelessList() { const objDev = [ { id: 1, surename: "John", name: "Wayne" ...

What is the process for reading server responses following the delivery of an alert to a designated user through socket.io?

Recently, I started exploring Socket.io and encountered an interesting challenge. My goal is to retrieve real-time location data from an Android device. To achieve this, I developed a basic application to access the current GPS coordinates. Additionally, I ...

Practical strategy for developing and launching a TypeScript/Node.js application

I'm currently developing a node.js app using Typescript, which requires compilation to JS before running. As someone with a background in java/jvm, I'm hesitant about the deployment process where code is pushed to git, built/compiled on the serve ...

How can you dynamically change visibility in AngularJS depending on the text within the element?

Consider the following HTML snippet: <p id="message" ng-show="something"></p> As the page loads, the #message element may be populated with text from an AJAX request. I want to show or hide #message based on whether it has content or not. S ...

What is the best way to implement a "param" feature similar to React's onChange and onClick methods?

I am interested in replicating the functionality of React's onClick, onChange, etc. An example of how React does this is: onClick={(event)=>console.log(event)} My goal is to achieve a similar effect using my custom property: someProp={(wanna_do_t ...

When executing npm run dev, an UnhandledPromiseRejectionWarning is triggered

I'm encountering an UnhandledPromiseRejectionWarning error when running npm run dev on my Vagrant machine, and I'm struggling to identify the root cause. The console output suggests that a promise is not being properly completed with the catch() ...

The art of combining arrays of objects while eliminating duplicates

I am in need of a solution to compare two object arrays, remove duplicates, and merge them into a single array. Although I am relatively new to javascript/Typescript, I have come across some blogs suggesting the use of Map, reduce, and filter methods for t ...

ensure that html tags display properly when retrieved from json in an angular directive template

Trying to embed ruby tags in a directive template but struggling with escaping them. Despite reading about $sce and filters, the confusion deepens as browser tabs multiply. The directive code is as follows: angular.module("ngFlashCard", ["ngSanitize"]).d ...

Ways to conceal the picture

Check out the JSfiddle link here for the full code. I'm having trouble with my slider as the last picture keeps collapsing underneath and is not hidden as it should be. I suspect this issue is causing the slider to malfunction. HTML <div class=" ...

Creating a shared component for restricting input to only numbers in ReactJS with Material-UI TextField

I am currently working with MUI TextField and my goal is to implement a validation that allows only numbers but not the eE+- keys. I aim to create a standard component for this using onChange event. I need to address the scenario where if the user enters ...