A different approach to onEnter in ui-router

Is there a way to avoid the double loading of routes in AngularJS when trying to dynamically load a route based on a user's most recent visit to a child route? Currently, I am using onEnter but it causes the parent route to load first and then a second load happens to load the child route. Can we prevent this second load and directly go to the child route if the necessary information is already available?

(function() {
    'use strict';

    angular
        .module('curation')
        .config(routesConfig);

    routesConfig.$inject = ['$stateProvider'];
    /**
     * Route Configuration to define URL patterns for the module
     * @param {Function} $stateProvider
     */
    function routesConfig($stateProvider) {
        // Curation state routing
        $stateProvider.
        state('site.curation', {
            url: '/curation',
            templateUrl: 'modules/curation/views/curation.client.view.html',
            resolve: {
                publicFronts: function($stateParams, frontsService) {
                    return frontsService.getPublicFronts($stateParams.siteCode);
                },
                authoringTypes: function(assetMetadata) {
                    return assetMetadata.authoringTypes().then(function(value) {
                        return value.data.authoringTypes;
                    });
                }
            },
            onEnter: function($state, $timeout, userSitePreferences, publicFronts) {
                $timeout(function() {
                    var recentFront = _.find(publicFronts, {
                        Id: userSitePreferences.curation.recentFrontIds[0]
                    });
                    if (recentFront) {
                        $state.go('site.curation.selectedFront.selectedLayout', {
                            frontId: recentFront.Id,
                            layoutId: recentFront.LayoutId
                        });
                    }
                });
            }
        });
    }
})();

Answer №1

Check out the "Deep State Redirect" feature of the "ui-router-extras".

Give this a try...

    $stateProvider.
    state('site.curation', {
        url: '/curation',
        templateUrl: 'modules/curation/views/curation.client.view.html',
        resolve: {
            publicFronts: function($stateParams, frontsService) {
                return frontsService.getPublicFronts($stateParams.siteCode);
            },
            authoringTypes: function(assetMetadata) {
                return assetMetadata.authoringTypes().then(function(value) {
                    return value.data.authoringTypes;
                });
            }
        },
        deepStateRedirect: {
            default: {
                state: 'site.curation.selectedFront.selectedLayout'
                params: {
                    frontId: 'defaultId',
                    layoutId: 'defaultLayout'
                }
            },
            params: true,
            // If you've never experimented with dynamic params before, it's worth giving it a shot and see if DI variables work.
            fn: function ($dsr$, userSitePreferences, publicFronts) {
                var recentFront = _.find(publicFronts, {
                    Id: userSitePreferences.curation.recentFrontIds[0]
                });
                if (recentFront) {
                    return {
                        state: $dsr$.redirect.state,
                        params: {
                            frontId: recentFront.Id,
                            layoutId: recentFront.LayoutId
                        }
                    };
                } else {
                    return false;
                }
            });
        }
    });

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

When integrating react-router 5 and redux 7, there is an issue where the state is not being reset when navigating to a new route using react-router's <Link

My current setup includes the following versions: `"react-router": "^5.2.0",` `"react-router-domreact-router": "^5.2.0",` I'm unsure if my setup is compatible with React-router 5 as I was using a version prior ...

Which is more effective for a webpage that solely calculates a formula: user input fields in DIVs or forms?

My idea is to create a webpage with initially 6 input fields, which can expand to 7, 8, 9, or 10 fields when a button is pressed. These fields will have editable preset values that will be used to calculate a final value using a formula. Should I use f ...

Configuring a timeout for your Next.JS API can help optimize the performance

Due to restrictions on another API, my own API takes 10 minutes to return a result. When running locally, I am able to wait and successfully receive the data after 10 minutes. However, when deployed on Vercel, I encounter a timeout error (status code 504). ...

The returned data from a Apollo Client useMutation call is consistently undefined

Currently, I have a code snippet that executes a mutation to update a post to "published." The mutation functions correctly and updates the data as intended. However, I am facing an issue where the data property remains undefined in the useMutation hook. S ...

Executing Javascript without invoking the default behavior

Recently, I've been delving into the world of JavaScript and experimenting with the prevent default command for ajax pagination. Here's the code I've come up with: http://jsfiddle.net/6pqfH/2/ $('.pagination').click(function(e){ ...

Issue with using GET fetch request in JavaScript-ReactJS app

I'm currently attempting to make a basic GET request from my ReactJS application to a Node.js API. However, I am encountering a 304 status response instead of the desired 200 status. My goal is to store the response from the GET request in a variable. ...

Guide to simulating a scope in an Angular unit test using a directive instead of a controller

Recently, I have been working on understanding how to mock a $scope and controller using the $controller constructor. var scope = rootScope.$new(); it('should contain a testVar value at "test var home"', function(){ homeCtrl = $controller(&a ...

Setting up angular-cli project for rc5- Step by step guide

Trying to integrate angular-cli with angular 2 rc5 but facing challenges: The issue of 'Promise' not being found After attempting to install 'npm install -g angular-cli@webpack', typings did not get installed, resulting in WebStorm un ...

Error encountered: The initMap function from the React Google Maps API is not recognized. No relevant

Encountering an issue where initMap is not recognized as a function. I attempted to avoid utilizing any additional packages for asynchronously loading the script or Google Maps API. My initial approach was to simply console log initMap to track when the sc ...

Submitting option values in AngularJS: A step-by-step guide

Why does AngularJS ng-options use label for value instead of just the value itself? Here is my current code: <select ng-model="gameDay" ng-options="gameDay for gameDay in gameDayOptions"> This currently displays: <select ng-model="gameDay" ng- ...

Avoid loading cached images stored in the HTML5 FileSystem API

Utilizing the FileSystem API, I am actively saving images to the HTML5 filesystem. Every few minutes, these images are reloaded and replaced from a server side function. Following each reload and replacement cycle, these images are displayed on a website. ...

"Enhance your website with Wordpress and Divi by adding dynamic image replacement on hover

In search of a code to insert into my project Utilizing images to create a large interactive button I'm currently using the divi code module within WordPress. I am seeking the ability to have an image switch with another image when hovering over it, ...

What is the best way to display tip boxes for content that is added dynamically?

One of the challenges with my web page is that dynamically added content does not display tipboxes, unlike items present since the page load. I utilize the tipbox tool available at http://code.google.com/p/jquery-tipbox/downloads/list. To illustrate the i ...

Interacting with individual divisions on a leaflet map

I've been facing a challenge with this interaction for some time now, and finding the appropriate solution seems quite daunting at the moment. Recently, I created a map with basic points using GeoJSON format (generated with PHP & MySQL). I'm cur ...

Tips for implementing $anchorScroll exclusively for mobile browsers/devices

As a newcomer to angularjs, I managed to successfully implement the anchorScroll feature. However, one question remains: Is it feasible to enable the anchorScroll only when a mobile device is detected? If so, how do I integrate this into my controller? T ...

Exploring the capabilities of the jQuery `val()` function alongside the dynamic framework

Whenever I have a JavaScript variable that contains HTML printed from a table on my server, I encounter issues when using it in a jQuery function like val(). The problem arises every time someone enters content with special characters like " or '. Thi ...

After a prolonged period of running, rendering webgl in requestAnimationFrame was only achieving 1 frame per second

While trying to render a WebGL animation using requestAnimationFrame, I noticed that it runs at 60fps for a period of time before suddenly dropping down to 1 fps. After approximately 500-1000ms, it goes back up to 60 FPS again. I am utilizing three.js to ...

`Using top-level await in a module can interfere with the firing of the `onload` event

It seems that the load event is not triggering when I use await for an IndexedDB opening at the top level within an indirectly loaded module. Interestingly, if I remove the await, the load handler works as expected. Similarly, replacing the openDB call wi ...

How can I implement a hover effect without triggering a click event?

My structure is pretty basic, here it is: .container { height: 100vh; width: 100%; pointer-events: none; } .click-layer { background-color: #ccc; position: absolute; top: 0; left: 0; right: 0; bottom: 0; pointer-events: auto; } .box { ...

Setting up a MEAN stack in Windows 7: A comprehensive guide

After completing a node.js server installation, I verified the command prompt by running node --version https://i.sstatic.net/wIHxX.png https://i.sstatic.net/Nb0qN.png Despite these steps, I encountered issues trying to start npm. ...