简体   繁体   English

Angular UI-Router:$ state.current有时是未定义的

[英]Angular UI-Router: $state.current is sometimes undefined

I'm using ui.router in my angular app, and in my navbar controller (which is included in more than one template) I wrote a simple console.log($state.current) to test it's behavior. 我在我的角度应用程序中使用ui.router ,在我的导航栏controller (包含在多个模板中)中,我编写了一个简单的console.log($state.current)来测试它的行为。

I've noticed that, sometimes, upon reload, the state is undefined: 我注意到,有时,在重新加载时,状态是未定义的:

Object {name: "", url: "^", views: null, abstract: true}

and sometimes it is defined: 有时它被定义:

Object {url: "/admin", templateUrl: "app/components/admin-dashboard/admin-dashboard.html", controller: "AdminCtrl", controllerAs: "vm", name: "admin-dashboard"}

What might be the cause of this behavior and how can I guarantee that my state is defined when the view is loaded? 可能是这种行为的原因是什么?如何保证在加载视图时定义我的状态?

Surest way to get the right value in $state.current is to wait for the $stateChangeSuccess event to be fired by ui-router. $state.current获得正确值的$state.current是等待ui-router触发$stateChangeSuccess事件。 Here's how you can do it: 这是你如何做到的:

In your Navbar controller: 在Navbar控制器中:

$rootScope.$on('$stateChangeSuccess', 
function(event, toState, toParams, fromState, fromParams){ 
    event.preventDefault(); 
    console.log($state.current)  // this should now always have a resolved value
})

Refer ui-router wiki for more details. 有关更多详细信息,请参阅ui-router wiki

Why this works as against only doing a console.log($state.current) is because, $state.current has the right value only 'after' the route is fully loaded. 为什么这种工作方式只针对做console.log($state.current)是因为,$ state.current有“后”的路线是满载只有合适的值。 When you write it without the event, depending on where you write it, it can be a hit or miss. 当你在没有事件的情况下编写它时,根据你写它的位置,它可能是命中或错过。 That's why you were getting inconsistent results. 这就是你得到不一致结果的原因。 It's exactly for this reason that ui-router provides a success event, which promises that route has definitely been resolved. 正是由于这个原因,ui-router提供了一个成功事件,它承诺该路由已经得到了解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM