0

我第一次使用 angular,在我的 index.html 文件中显示一些动态信息时遇到了一些麻烦。ng-view 标记内的所有内容都运行良好。

当用户进行身份验证时,带有用户信息的全局变量会被放入 $rootScope 和 cookie 中。我尝试通过执行类似 {{$rootScope.globals.currentUser.username}} 的操作来访问索引中的 $rootScope,但它不起作用。所以考虑下面的代码,我怎样才能在我的 index.html 中显示记录的用户信息?

我尝试在我的 app.js 中创建一个控制器并将 ng-controller 放在主体上。虽然这有效,但在用户注销时它不会刷新(需要刷新页面以更新应用程序控制器)。用户登录后也会发生同样的情况(需要刷新整个页面才能显示信息)。

在 $rootScope 中设置 cookie 和对象的代码。

function SetCredentials(username, password, token) {
  $rootScope.globals = {
    currentUser: {
      username: username,
      token: token
    }
  };

  $http.defaults.headers.common['Authorization'] = 'Bearer ' + token;
  $cookies.put('globals', JSON.stringify($rootScope.globals));
}

我还有以下 index.html 文件。如您所见,我已设置 {{$rootScope.globals.currentUser.username}} 但用户登录后没有显示

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <base href="/" />
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>My App</title>
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <!-- css references -->

</head>

<body class="hold-transition skin-blue sidebar-mini">
    <div class="wrapper">
        <!-- Main Header -->
        <header class="main-header">
            <!-- Header Navbar -->
            <nav class="navbar navbar-static-top" role="navigation">
                <!-- Sidebar toggle button-->
                <a href="#" class="sidebar-toggle" data-toggle="offcanvas" role="button">
                    <span class="sr-only">Toggle navigation</span>
                </a>
                <!-- Navbar Right Menu -->
                <div class="navbar-custom-menu">
                    {{$rootScope.globals.currentUser.username}}
                </div>
            </nav>
        </header>
        <!-- Content Wrapper. Contains page content -->
        <div class="content-wrapper">
            <ng-view></ng-view>
        </div>
        <!-- /.content-wrapper -->
        <!-- Main Footer -->
        <footer class="main-footer">
            <!-- To the right -->
            <div class="pull-right hidden-xs">
                something here
            </div>
            <!-- Default to the left -->
            <strong>Copyright &copy; 2016 <a href="#">NPF</a>.</strong> All rights reserved.
        </footer>
    </div>
    <!-- ./wrapper -->
    <!-- REQUIRED JS SCRIPTS -->
    <!-- jQuery 2.2.0 -->
    <script src="Scripts/jquery-2.2.3.js"></script>
    <script src="Scripts/bootstrap.js"></script>
    <script src="Scripts/app.min.js"></script>

    <script src="Scripts/linq.min.js"></script>
    <script src="scripts/angular/angular.min.js"></script>
    <script src="scripts/angular/angular-route.min.js"></script>
    <script src="scripts/angular/angular-resource.min.js"></script>
    <script src="scripts/angular/angular-cookies.min.js"></script>

    <!-- application scripts -->
    <!-- Main app -->
    <script src="app/app.js"></script>

    <!-- controllers -->
    <script src="app/home/home.controller.js"></script>

    <!-- services -->
    <script src="app/services/authentication.service.js"></script>
    <script src="app/services/user.service.js"></script>
</body>
</html>

我的应用程序文件如下

(function () {
'use strict';

angular
    .module('myApp', ['ngRoute', 'ngCookies', 'treeControl'])
    .constant("appSettings",
    {
        serverPath: "http://localhost:64789/",
        webApiPath: "http://localhost:64789/api/"
    })
    .config(config)
    .run(run);

config.$inject = ['$routeProvider', '$locationProvider'];
function config($routeProvider, $locationProvider) {

    $locationProvider.html5Mode({
        enabled: true,
    });

    $routeProvider
        .when('/', {
            controller: 'HomeController',
            templateUrl: 'app/home/home.html',
            controllerAs: 'viewModel'
        })

        .when('/login', {
            controller: 'LoginController',
            templateUrl: 'app/login/login.html',
            controllerAs: 'viewModel'
        })

        .when('/register', {
            controller: 'RegisterController',
            templateUrl: 'app/register/register.html',
            controllerAs: 'viewModel'
        })

        .otherwise({ redirectTo: '/login' });
};


run.$inject = ['$rootScope', '$location', '$cookies', '$http'];
function run($rootScope, $location, $cookies, $http) {
    // keep user logged in after page refresh
    try {
        $rootScope.globals = JSON.parse($cookies.get('globals'));
    }
    catch (err) {
        $rootScope.globals = {};
    }

    if ($rootScope.globals && $rootScope.globals.currentUser) {
        $http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.globals.currentUser.token;
    }

    //config.headers.Authorization = 'Bearer ' + authData.token;

    $rootScope.$on('$locationChangeStart', function (event, next, current) {
        // redirect to login page if not logged in and trying to access a restricted page
        var restrictedPage = $.inArray($location.path(), ['/login', '/register', '/gds']) === -1;
        try {
            var loggedIn = $rootScope.globals.currentUser;
        }
        catch (err) {

        }
        if (restrictedPage && !loggedIn) {
            $location.path('/login');
        }
    });
}})();
4

1 回答 1

0

正如我在评论中提到的那样$rootScope,HTML 标记表达式不需要。

但是,如果您忘记在 ng-view 之外的 HTML 中添加控制器,这也可能导致变量未定义。(没有控制器 = 没有 $scope)

于 2016-04-21T09:34:11.553 回答