【问题标题】:Authentication with JWT how to force Angular App to refresh使用 JWT 进行身份验证如何强制 Angular App 刷新
【发布时间】:2016-05-27 03:49:08
【问题描述】:

我正在构建一个 MEAN Stack 应用程序,使用 JWT 和 Passport 进行身份验证,我能够在登录时将令牌保存在本地存储中并在注销时将其删除,这很完美,但是 Angular 应用程序的状态如何用户登录时不更新状态。 更新状态的唯一方法是手动刷新。 我试过state.reload();$state.go('.', {}, { reload: true }); 和几乎所有的东西,唯一有效的是$window.location.href = '/';,但这没有任何意义,因为我想使用 ui-router 状态。 是否可以强制执行摘要循环或更新状态的东西?

这是我拥有的代码的 sn-p:

vm.doLogin = function() {
  vm.formError = '';
  authentication
    .login(vm.credentials)
    .error(function(err) {
      vm.formError = err.message;
    })
    .then(function() {
      $state.go('.', {}, { reload: true });
    });
};

我将非常感谢一些帮助。

【问题讨论】:

    标签: angularjs passport.js jwt mean


    【解决方案1】:

    您是否尝试过使用$state.go($state.current, {}, {reload: true});
    或者您可以使用 $route.reload(); 重新初始化您的控制器

    var currentPageTemplate = $route.current.templateUrl;
    $templateCache.remove(currentPageTemplate);
    $route.reload();
    

    模板被缓存。如果这是您想要遵循的方式,那么您需要在调用 reload 之前从 $templateCache 中删除模板。

    另一个选项是在登录后到达的视图中使用 cache-view=false,如果您在维护该特定视图中的动态状态时遇到问题。

    $window.location.reload(); //reinitializes the controller as well as the services however, forcing the hard reload is bad.
    

    【讨论】:

      【解决方案2】:
      "home" is my abstract state which will host my modules.
      "module1"&"module2" are two modules within "home"
      
       State definitions as follows.
      
          $stateProvider.state('login', {
                  url: "/login",
                 templateUrl: "app/login/login.html",
                   controller: 'LoginController'
                 })
      .state('home', {
                  url: "/home",
                  abstract: true,
                  templateUrl: "<div ui-view></div>"
                 })
              .state('home.module1', {
                       url: "/module1home",
                       templateUrl: "app/module1/module1.home.html",
                       controller: 'Module1HomeController'
      
                   })
      
                   .state('home.module2', {
                       url: "/module2home",
                       templateUrl: "app/module2/module2.home.html",
                       controller: 'Module2HomeController'
      
                   });
      
       After successful login use the below code to navigate to "/home/module1home"(which ever default state's url) which in turn trigger the state.
      
       $location.path('/home/module1home');
      

      【讨论】:

        猜你喜欢
        • 2021-05-17
        • 2017-11-25
        • 1970-01-01
        • 2014-07-06
        • 2016-04-07
        • 2019-08-30
        • 2019-09-27
        • 2023-03-27
        • 2021-05-29
        相关资源
        最近更新 更多