【问题标题】:How to get the Previous State with Params using ui-router如何使用 ui-router 获取带有参数的先前状态
【发布时间】:2017-09-15 00:10:27
【问题描述】:

问题陈述:

我有一个“添加评论”按钮,我应该只有登录系统才能添加评论。

但问题是我登录后无法返回“添加评论”页面,因为我不知道之前的状态或无法获取之前的状态。

有没有更清洁的解决方案?我应该让登录页面成为模式而不是新页面吗?

我已经看到了有关先前状态的所有问题以及可能的答案(是的,我正在考虑 $rootscope 和 $stateChangeSuccess)。但并未明确提出解决方案。

其他可能的解决方案如下 http://christopherthielen.github.io/ui-router-extras/example/previous/index.html#

我也看到了 https://github.com/angular-ui/ui-router/issues/92。但同样,我不确定正确的答案是什么。

有人能清楚地说明一个好的解决方案吗?使用 rootscope 好用吗?

【问题讨论】:

  • 您可以在登录状态添加returnUrl参数(或returnState),然后在重定向到登录状态时设置它。
  • 我想到了这个解决方案。但随后我需要考虑要与返回 url 一起传递的参数。这使得这有点乏味

标签: angularjs angularjs-scope angular-ui-router angular-ui-router-extras


【解决方案1】:

我应该让登录页面成为模态页面而不是新页面吗? 这是一个设计决策。您可以根据自己的喜好选择适合您的应用的任何内容。

使用 rootscope 好吗? 我觉得它是一个很好的解决方案。以下是我的做法:

手动保存之前的状态:

创建状态变化监听器:

    $rootScope.$on('$stateChangeSuccess', function(event, to, toParams, from, fromParams) {
        //save the previous state in a rootScope variable so that it's accessible from everywhere
        $rootScope.previousState = from;
    });
  }]);

不要使用ui-sref,而是为评论按钮添加一个点击功能。

$scope.commentHandler = function(){
    //check if user is logged in, let the user post the comment

    //else take him to login page
}

然后您可以在用户登录后使用$state.go($rootScope.previousState.name)返回评论页面。

-或-

如果用户未登录,您可以提供一个小的登录框来代替“发表评论”按钮。

【讨论】:

    【解决方案2】:

    对于 ui-router v1.0.0+,状态更改事件为deprecated

    Arjun's 状态变化监听器的更新版本将是

    $transitions.onStart({}, function (transition) {
        $rootScope.previousState = transition.from();
    });
    

    【讨论】:

      猜你喜欢
      • 2013-05-14
      • 2014-08-21
      • 1970-01-01
      • 1970-01-01
      • 2016-08-11
      • 2016-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多