【问题标题】:angular-ui-router $stateChangeStart Event Not Firing in Angular Webpack ES2015 Component BuildAngular Webpack ES2015 组件构建中未触发 angular-ui-router $stateChangeStart 事件
【发布时间】:2016-04-25 12:56:35
【问题描述】:

我正在尝试以 Angular 实现前端 JWT 身份验证,但 $stateChangeStart 事件未在状态之间触发。我使用的是用 es2015 编写并与 Webpack 捆绑在一起的基于组件的架构。

当我在状态之间切换时,在运行块中设置的 $stateChangeStart 侦听器不会触发。

app.js 是应用程序的入口点。我将其他角度模块作为组件包含在内。

import 'normalize.css';
import {appDirective} from './app.directive';

// Angular Dependencies
import angular from 'angular';
import uiRouter from 'angular-ui-router';
import ngAnimate from 'angular-animate';

// JWT Dependencies
import angularJwt from 'angular-jwt';
import angularStorage from 'angular-storage';

// Import shared services
import {services} from './services/services';

// Import components
import {signup} from './components/signup/signup';
import {login} from './components/login/login';
import {dashboard} from './components/dashboard/dashboard';

angular.module('app', [
  uiRouter,
  ngAnimate,
  angularJwt,
  angularStorage,

services.name,

signup.name,
login.name,
dashboard.name

])
.directive('app', appDirective)

// config $httpInterceptors to attach JWT tokens

.run(function($rootScope, $state, Auth) {
  $rootScope.$on('$stateChangeSuccess', function(e, to){
    // Check for authentication, but function does not execute
  });
});

这是组件入口点文件的示例。我为这些文件中的每个组件设置了状态。

import {dashboardDirective} from './dashboard.directive';
import angular from 'angular';
import uiRouter from 'angular-ui-router';

export const dashboard = angular.module('dashboard', [uiRouter])
  .config(($stateProvider) => {
    $stateProvider.state('dashboard', {
      url: '/dashboard',
      template: '<dashboard></dashboard>',
      authenticate: true
    });
  })
  .directive('dashboard', dashboardDirective);

使用主应用程序模块上的 .run 块来设置状态更改的侦听器在其他应用程序架构中可以正常工作,但我似乎无法理解为什么它在这里不起作用。

【问题讨论】:

    标签: javascript angularjs angular-ui-router components webpack


    【解决方案1】:

    这应该会触发 $stateChangeStart 监听器运行。

    $stateProvider.state('dashboard', {
      url: '/dashboard',
      template: '<dashboard></dashboard>',
      authenticate: true,
      resolve: {
        data: function($q) {
          var deferred = $q.defer();
    
          setTimeout(function() {
            deferred.resolve();
          }, 1000);
    
          return deferred.promise;
        }
      }
    });
    

    【讨论】:

      【解决方案2】:

      要使用状态更改事件,您必须重建包含 stateEvents.ts 的库。它们已被弃用,最好使用这些功能。有一些语法糖可以让这变得简单。

      .state('home', {
          url: '^/home/',
          onStart: ['$transition', '$state', function( transition, state){
          //your handling of this event
          });
      

      您的帖子在 TS 中,所以希望您能翻译一下。您可以详细了解如何利用状态生命周期here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-23
        • 1970-01-01
        • 2022-06-30
        • 2016-12-06
        • 2016-10-05
        相关资源
        最近更新 更多