Cannot read property "@" null when using $ state in onEnter

I get the following error from angular -ui-router:

TypeError: Cannot read property '@' of null ... TypeError: Cannot read property '@main' of null ... 

I did some research on what could be causing this error, and came to the conclusion that the problem is that I am redirecting when the condition is false through the state $ state.go (state) during the onEnter of another state.

Here are some discussions regarding the same issue on github:

I tried some of the suggestions, but they do not work. They don't seem to give a solution, they just point to a problem, and according to this github discussion should be resolved, but I can. It seems to work.

I am using AngularJS v1.2.24 and ui-router v0.2.11.

Using the following code (simplified):

 .state('main', { abstract: true, url: '/main', templateUrl: '/main/_layout.html' }) .state('main.home', { url: '/home', templateUrl: '/main/home/home.html', controller: 'HomeCtrl', onEnter: function ($state) { if (condition === true){ $state.go('main.catch') } } }) .state('main.catch', { url: '/catch', templateUrl: '/main/catch/catch.html', controller: 'CatchCtrl' }) 

Is there any way to make this work? Or should I consider a completely different approach to achieving the same result?

PS: A possible fix is ​​to do the following in the controller,

 $scope.$on('$stateChangeSuccess', function(){ // conditional redirect here } 

But I do not want to do this in HomeCtrl.

+5
source share
2 answers

I came across a similar situation and solved it like this:

 .state('main.home', { url: '/home', templateUrl: '/main/home/home.html', controller: 'HomeCtrl', onEnter: function ($state) { if (condition === true){ $timeout(function() { $state.go('main.catch') )}; } } }) 

The trick is that you want the original state to change, rather than trying to redirect in the middle of the state change. The $ timeout allows you to complete the initial state change, and then immediately turn off the change to the desired state.

+1
source

Well, I know this a little late, but I had this problem for a long time, and I finally solved it by listening to the $viewContentLoading event:

 $rootScope.$on('$viewContentLoading', function(){ if(!$state.$current.locals) $state.$current.locals = {}; }); 
0
source

Source: https://habr.com/ru/post/1213693/


All Articles