Double triggering of $stateChangeStart event in Angular UI Router (extras)

I'm having trouble understanding why the addition of Angular UI Router Extras causes the $stateChangeStart event to trigger twice (on init!) in a situation where I have some asynchronous ajax check and call e.preventDefault().

Here is a short example of the event code:

 $rootScope.$on("$stateChangeStart", function (e, toState, toParams, fromState, fromParams, error) {
       console.log("$stateChangeStart");//fired twice
       if(!User.data) {
             e.preventDefault();
             $http.get("https://randomuser.me/api/")
             .success(function(data, status, headers, config) {
                  console.log(data);
                  User.data = data; 
                  $state.go(toState, toParams);
              });
       }              
 });

Here's the full FIDDLE Example

Everything works as expected without using the extras addition.

Thank you!

Answer №1

Angularjs undergoes multiple checks in its digest cycle to examine changes before and after, which might be a part of that cycle.

This behavior can be observed when using $watch.

$scope.$watch('myVariable', function(change) {
  if (!change) { return; }
  // perform important tasks here.
});

During the initial round of the digest cycle, the change parameter will initially be undefined, until myVariable is assigned a value elsewhere. Once myVariable gets set somewhere else, the $watch function will trigger again and bypass the if block to execute actual work.

If this scenario applies to your code, you may consider adding an if block to exit the function if any of your parameters are undefined or hold values on which you do not wish to act upon.

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

  if (!e || !toStateForExample || anotherParameter) { return; }

  console.log("$stateChangeStart"); // triggered twice
  if (!User.data) {
    e.preventDefault();
    $http.get("https://randomuser.me/api/")
      .success(function(data, status, headers, config) {
        console.log(data);
        User.data = data;
        $state.go(toState, toParams);
      });
  }
});

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

How can we avoid animations being interrupted by user interaction?

My webpage has an animation that runs smoothly on desktop, but stops as soon as I interact with the page on a touch device. I have tested this issue on Chrome and Safari on iPad. I'm curious if this behavior is intentional on the part of browser vend ...

React Link updates the browser's URL without refreshing the page, yet fails to display any new content

Currently, I am working on developing a chat application where I am facing an issue with matching the id parameters to display each one upon clicking. The core components I am dealing with include Chatroom.js and RoomList, which acts as the navigation menu ...

The proper method for clearing out all items from the environment

Although there are numerous questions on SO that address the topic of removing everything from a scene, none of the methods I've tried seem to work as expected. There isn't a definitive solution provided in the documentation either, so I'm h ...

Whoops! Unable to interpret properties from an undefined source while trying to retrieve 'get'

Every time I execute my program, I encounter the following error: Cannot read properties of undefined (reading 'get') TypeError: Cannot read properties of undefined (reading 'get') at Proxy.mounted (webpack-internal:///./node_module ...

How to set the default value of a dropdown list created using ng-repeat in AngularJS

My challenge lies in creating a select list from an associative array using ng-repeat. The ng-model of the list is tied to a scope variable with an initial value, but the options generated do not initialize with this value. I suspect this has to do with th ...

Interacting with the header component within the renderHeader property of the MUI Data Grid Pro will update the sortModel

Currently, I am utilizing the Material UI DataGridPro component to construct a React Js application. I am interested in developing a customized filtering feature. In the image below, you can see a red box representing an IconButton for the filtering view ...

Export buttons in Jquery datatable are malfunctioning

I have been attempting to include export buttons for Excel and PDF in a jquery data table using its extension, but I am facing an issue where the buttons are not showing up above the table. Despite trying various other solutions from different sources, I ...

Is it possible to identify users using an iPhone while they are utilizing "Private Browsing" mode?

Looking for a solution to detect private browsing mode in my jquerymobile App. I need localStorage and sessionstorage to work properly, but prompting users to enable cookies when private browsing is enabled doesn't solve the issue. Is there a way to t ...

Managing the sequence of module loading in NodeJS

Consider this scenario: There are 3 files (modules) involved: app.js (async () => { await connectoDB(); let newRec = new userModel({ ...someprops }); await newRec.save(); })(); The app.ts serves as the entry point of the project. database ...

The material-table component in React seems to have trouble displaying data when using the onRowAdd function, but at least the state

In my onRowAdd function, I first test if the input values are true before adding them to the table. The problem is that even though new data newData is added to the state when the input values are true, the material table does not display them. The data i ...

Using Google App Script's pageToken to store attachments on Google Drive

Essentially, my goal is to save all attachments from received emails to a specific folder in Google Drive (mostly .PDF files). However, I've encountered a limitation with the search function which only allows me to retrieve up to 500 attached files. I ...

Get immediate results in real-time

On a specific page, I have a form that I want to submit and receive a result upon submission. To display the returned data in a div, I've included this code: <script type="text/javascript"> $(function(){ $('#ff').form ...

Issue with inability to clear text in popup upon closure by jQuery

I am facing an issue with a popup menu that contains an iframe code as text. There is a button to enable the iframe code text, and I need to disable it or set it to display:none when the popup is closed. This means every time I reopen the popup, I have to ...

Discovering the selected option's value in a dropdown and utilizing it to search through an array for data to fill another input

Is there a way to utilize the value of a select input option, created by a forEach loop, to extract the value of another property in the same array object and assign it as the value of a different input field? Apologies if this seems verbose or has been a ...

Tips for passing props while clicking on a v-data-table:

I am currently facing an issue in my app while using v-data-table. I am able to pass props with an extra slot, but I want the entire row to be clickable in order to open a dialog with the prop item: <template v-slot:item.actions="{ item }"> ...

A guide on implementing dynamic ng-models in Angular

Struggling with creating dynamic ng-models in Angular. I've tried several methods but keep getting undefined as a result. Here is the code snippet I am working with: <input type="text" class="form-control input-sm" ng model="teller[value.teller_id ...

Preventing the JSF form from automatically scrolling to the top of the screen following an AJAX request

Is there a way to prevent the JSF form from moving to the top of the screen after an AJAX call? I have searched for solutions, but the answers seem outdated or not specific to JSF. Is there a simple technique in JSF that can stop the form from jumping back ...

The active class in the Bootstrap carousel is not updating when trying to change

I am struggling to make the Twitter Bootstrap carousel function properly. Although the slides automatically change after the default timeout, the indicators do not switch the active class, resulting in my carousel failing to transition between slides. Ini ...

I am attempting to set up a file download feature, but every file I download ends up either being corrupted in the case of images or empty for PDFs

I'm having issues with a file download feature I'm working on. Whenever I try to download a file, it ends up being corrupted (image) or empty (pdf). Can anyone help me identify what I might be doing wrong? axios.post(`/master/api/Download?filenam ...

Top method for triggering an action on the client-side during Sign In with the help of Redux, React, and NextAuth

Currently, I am developing a web application that utilizes the Spotify API. My goal is to seamlessly load the user's playlists as soon as they log in using NextAuth. At the moment, there is a button implemented to trigger playlist loading, but it onl ...