简体   繁体   English

使用 UI-router 导航到 fromState

[英]Use UI-router to navigate to fromState

AngularJS UI-router has a useful parameter "fromState" which allows me to store where the user came from when they change state. AngularJS UI-router 有一个有用的参数“fromState”,它允许我存储用户在更改 state 时来自哪里。 I am trying to implement a system which takes the user back where they left off if they are taken to a subscribe / login / signup state.我正在尝试实现一个系统,如果用户被带到订阅/登录/注册 state,则该系统会将用户带回他们离开的地方。 I capture the fromState, they perform the action, then if my fromState var is set the user will be taken back to that state.我捕获 fromState,他们执行操作,然后如果我的 fromState 变量被设置,用户将被带回 state。 But it doesn't work: Example:但它不起作用:示例:

.run(function ($rootScope, $state, $timeout, $location, $anchorScroll) {
  $rootScope.$on('$locationChangeSuccess', function (event, toState, fromState) {
    $rootScope.loggedFromState = fromState;
    console.log($rootScope.loggedFromState);

Outputs "http:// my-app-url /page-name"输出“http:// my-app-url /page-name”

I would then like to do something like this:然后我想做这样的事情:

$state.go($rootScope.loggedFromState);

But that doesn't work.但这不起作用。 A state has to be a state name + params, but fromState is in a URL format. state 必须是 state 名称 + 参数,但 fromState 是 URL 格式。 How do I navigate to $rootScope.loggedFromState (" http://my-app-url/page-name ")?如何导航到 $rootScope.loggedFromState (" http://my-app-url/page-name ")?

A more appropriate way is to use ui-router hooks: https://ui-router.github.io/guide/transitionhooks更合适的方法是使用 ui-router hooks: https://ui-router.github.io/guide/transitionhooks

$transitions.onStart({}, function(transition) {
    console.log(
    "Transition from " + transition.from().name +
    " to " + transition.to().name
    );

    let from = transition.from().name;
    // validation
    // if validation fails abort transition
    transition.abort();
    // and redirect somewhere else
    $state.go(from);

});

Then you can take the state name:然后可以取 state 名称:

let from = transition.from().name;

first abort current transition:首先中止当前转换:

transition.abort();

and then redirect:然后重定向:

$state.go(from);

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

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