【问题标题】:Protect routes and redirect user based on some conditions with Angular ui-router使用 Angular ui-router 根据某些条件保护路由并重定向用户
【发布时间】:2016-12-01 14:32:09
【问题描述】:

场景是:

对于我应用中的某些路线,我想强制用户先完成他们的个人资料。

有几种方法可以实现:

  1. 在用户解析中重定向(我们加载用户数据的地方)
  2. 监听$stateChangeStart事件,从服务器加载用户,检查配置文件是否完整

使用方法 1,是否可以将用户解析重用于其他路由(考虑到用户解析挂起在 auth resolve 上的事实)?

使用方法 2,我觉得这种方法容易出错且难以跟踪。

这个问题有什么最佳实践吗?

【问题讨论】:

  • 首先,您可以在服务中使用 resolve 并重用它。

标签: angularjs angular-ui-router


【解决方案1】:

您可以在resolve 中使用service 将routes 和reuse 中的代码缩减为resolve function

这是它的一个示例实现。

$stateProvider
  .state('inbox', {
    ...
    resolve: {
      profile: function (UserService) {
        return UserService.getUser();
      },
    }
  })
  .state('dashboard', {
    ...
    resolve: {
      profile: function (UserService) {
        return UserService.getUser();
      },
    }
  });

您的控制器可以是,

angular
  .module('app')
  .controller('DashboardCtrl', DashboardCtrl);

function DashboardCtrl(profile,$scope) {
  this.user_profile = profile;
}

HEre is the reference

更新:

你可以在resolvelike中使用redirection,

resolve: {
  profile: function (UserService,$state) {
    return UserService.getUser().then(function(profile){
    if (profile.id) {
        return profile;
  } else {
        $state.go('/')
  }
  },
}

【讨论】:

  • 感谢您的回答。重定向代码在哪里?
  • 您可以从service 获取response,使用then promise 并在此处自行重定向。
  • 谢谢,我应该如何跨路由重用这个解析?
猜你喜欢
  • 1970-01-01
  • 2019-09-21
  • 2015-11-20
  • 2017-04-17
  • 2019-07-06
  • 1970-01-01
  • 2017-11-15
  • 2014-11-25
相关资源
最近更新 更多