ui.router状态不按预期方式工作

问题描述:

我正在使用ui.router来检测Angular App中的状态更改。但是控制器不会在加载时被调用。ui.router状态不按预期方式工作

以下是我的app.js的代码。

var admin = angular.module('admin',['admin.core']); 
    angular.module('admin.core', ['ui.router', 'satellizer', 'ngMaterial']); 

    admin.config(function($mdThemingProvider, $stateProvider, 
          $urlRouterProvider, $authProvider, $locationProvider){ 
    $mdThemingProvider.theme('default').primaryPalette('light-blue', { 
     'default': '700', 
     'hue-1' : 'A200', 
    }).accentPalette('blue'); 

    // Satellizer configuration that specifies which API route the JWT should be retrieved from 
    $authProvider.loginUrl = '/api/authenticate'; 

    // Redirect to the auth state if any other states are requested other than users 
    $urlRouterProvider.otherwise('/admin/login'); 
    console.log($stateProvider) 
    $stateProvider 
     .state('login', { 
      url: '/admin/login', 
      name: 'login', 
      controller: 'AuthController as auth', 
     }) 
     .state('users', { 
      url: '/admin/users', 
      controller: 'UserController as user' 
     }); 
     $locationProvider.html5Mode(true); 
    }); 

    admin.controller('AuthController', AuthController); 

    function AuthController($auth, $state, $scope) { 
    console.log("Called"); 
    var vm = this; 

    vm.login = function() { 
     var credentials = { 
      email: vm.email, 
      password: vm.password 
     } 
     console.log(credentials); 
     // Use Satellizer's $auth service to login 
     $auth.login(credentials).then(function(data) { 
      // If login is successful, redirect to the users state 
      $state.go('users', {}); 
     }); 
    } 

    } 

AuthController当我的状态是login不叫。

+0

为什么url:'users',而不是'/ users'?并添加名称:'用户' –

+0

@PiotrPęczek..更正 – Gags

+0

你有'ui-view'在你的根app html的某个地方吗? – devqon

使用$locationProvider.html5Mode(true);时,您必须提供基准href位置。它会将您的状态解析网址解析为http://localhost:8001/admin/#/login,并且应该解决您的问题。

尝试将<base href="/" />添加到主索引文件的<head />部分,以指定应用程序的基本路径。

https://docs.angularjs.org/api/ng/provider/$locationProvider

还提供您的服务器上.htaccess文件八方通重定向到邮件索引页面的具体要求。你可能必须调整它适合你的结构。

<IfModule mod_rewrite.c> 
    RewriteEngine On 
    RewriteBase/
    RewriteRule ^index.html$ - [L] 
    RewriteCond %{REQUEST_FILENAME} !-f 
    RewriteCond %{REQUEST_FILENAME} !-d 
    RewriteRule . /index.html [L] 
</IfModule> 

注意mod_rewrite的有我的Apache服务器上启用。通过 默认它被禁用。

+0

因为我在管理员,所以我的基地址将是''对吗?它只有第一次..意味着如果我访问'http:// localhost:8001/admin'那么stateprovider使它'http:// localhost:8001/admin/login',但现在如果我将使用刷新那么Controller不会被调用... – Gags

+0

因此,这可以解决您最初的问题?现在在'F5'/页面刷新时会出现新问题?正确? –

+0

您是否已将“.htaccess”添加到您的服务器?查看上面更新的答案。 –