javascript - 检查 localStorage 是否在 AngularJS 路由中有值的最简单方法

标签 javascript angularjs angularjs-routing

web 中的许多教程都有一点奇怪和庞大的 angularJS 条件路由逻辑...

我需要一些非常简单的东西:

只需检查一个组件,如果 localStorage 的 authFlag 为 true,则类似:

app.config(function ($routeProvider) {
  $routeProvider
      .when('/', {
          templateUrl: 'views/app.html',
          controller: 'AppCtrl'
      })
      .when('/articles', {
          templateUrl: 'views/articles.html',
          controller: 'ArticlesCtrl',
          conditions: { isAuth }
      })
      .otherwise({
          redirectTo: '/'
      });
});

怎么做比较好?检查 authFlag 是否在 localStorage 中,如果不在,则根目录到 '/' ?

最佳答案

需要添加解析,然后在解析函数中,添加对本地存储的检查, 如果不是,则路由到“/”:

在resolve函数中添加如下代码

resolve:{
    data:  function(){
        var result = window.localStorage.getItem("authFlag");

        if (result)
        {
            // do whatever you want to do
        }
        else
        {
            $location.path("/");
        }
    }
},

关于javascript - 检查 localStorage 是否在 AngularJS 路由中有值的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27875034/

相关文章:

javascript - 在 Javascript 中重置计数计时器

javascript - Angular Material select 在固定 block 上的行为很奇怪

javascript - AngularJS - 复选框和下拉列表

javascript - angularjs 复选框验证至少两个

javascript - $scope 在我的导航栏 Controller 中不起作用?

javascript - Angular route 的动态页面

javascript - 如何实现 Angular 指令以在导航到站点中的另一个页面时显示模式?

javascript - Kendo UI 窗口在页面滚动时的固定位置

javascript - Ajax响应返回空值。网络响应显示该值

javascript - Angularjs ui-router 无法从状态 'results/0' 解析 'survey'