无法让 $state 与 angular-ui-router 一起工作

can't get $state to work with angular-ui-router

我正在尝试使用 $state 进行简单的路由重定向。我无法让它工作。这是我的代码:

angular.module('starter', ['ionic', 'starter.controllers', 'starter.services', 'ng-token-auth'])

.run(function($ionicPlatform, $location, $rootScope, $state) {
  $ionicPlatform.ready(function($state) {

    $rootScope.$on('auth:login-success', function($state) {
      console.log('success event triggered yo main');
      // $location.path('main');
      $state.go('main');
    });

  });
})

.config(function($stateProvider, $urlRouterProvider, $authProvider) {
  $stateProvider

  // setup an abstract state for the tabs directive

  .state('main', {
    url: '/main',
    templateUrl: 'templates/main.html'
  })

  .state('home', {
    url: '/home',
    templateUrl: 'templates/home.html'
  })
  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/home');

});

这给了我以下错误:

ionic.bundle.js:25642 TypeError: $state.go is not a function
    at app.js:28
    at Scope.$broadcast (ionic.bundle.js:29477)
    at ng-token-auth.js:191
    at ionic.bundle.js:23384
    at processQueue (ionic.bundle.js:27879)
    at ionic.bundle.js:27895
    at Scope.$eval (ionic.bundle.js:29158)
    at Scope.$digest (ionic.bundle.js:28969)
    at Scope.$apply (ionic.bundle.js:29263)
    at done (ionic.bundle.js:23676)

我尝试从 $rootScope.$on 中删除 $state 但我得到了这个错误:

ionic.bundle.js:25642 TypeError: Cannot read property 'go' of undefined
    at app.js:28
    at Scope.$broadcast (ionic.bundle.js:29477)
    at ng-token-auth.js:191
    at ionic.bundle.js:23384
    at processQueue (ionic.bundle.js:27879)
    at ionic.bundle.js:27895
    at Scope.$eval (ionic.bundle.js:29158)
    at Scope.$digest (ionic.bundle.js:28969)
    at Scope.$apply (ionic.bundle.js:29263)
    at done (ionic.bundle.js:23676)

我该如何解决这个问题?

尝试从 $rootScope.$on 中删除 $state 参数。我觉得应该是:

$rootScope.$on('auth:login-success', function() {
      console.log('success event triggered yo main');
      // $location.path('main');
      $state.go('main');
});

通过将 $state 作为参数传递,您实际上是在这样做:

$rootScope.$on('auth:login-success', function($state) {
      var $state;
      console.log('success event triggered yo main');
      // $location.path('main');
      $state.go('main'); //undefined...
});

您可能还需要 $ionicPlatform.ready(function($state) {...。您正在定义回调函数...未传入 $state。你认为正在发生的事情不是。

您需要设置对 ui.router 模块的依赖:

angular.module('starter', ['ionic', .... , 'ui.router'])