为什么在重新加载路由时重新初始化 AngularJS 服务

Why is AngularJS service re-initialized when route is re-loaded?

本文关键字:初始化 AngularJS 服务 路由 加载 新加载 为什么      更新时间:2023-09-26

AngularJS服务被注入到两个单独的模块中。 这会导致服务在第二个模块调用它时单独重新初始化。我已经使用 FireFox 调试器来确认模块正在重新初始化。如何避免此问题?

具体情况如下:

AngularJS 应用程序在名为 auth 的模块中使用身份验证服务来管理身份验证问题。 auth服务被导入到一个message模块中,该模块管理对安全/message路由的访问,auth也被导入到一个navigation模块中,该模块管理登录/注册以及用户浏览器中导航链接的可见内容。 用户能够使用链接到navigation模块的 GUI 工具成功登录,然后作为经过身份验证的用户成功重定向到安全/message路由,因为auth.authenticated1auth.authenticated2属性在重定向到/message发生之前设置为true

但是,FireFox 调试器确认问题在于,当用户刷新浏览器以重新加载 /message url 模式时,auth 模块将重新初始化,将 auth.authenticated1auth.authenticated2 的值设置回 false,从而向用户显示一条消息,表明他们未登录,即使他们在使用用户提供的有效凭据之前登录了片刻。 需要对下面的代码进行哪些具体更改,以便用户在重新加载页面时不会注销?

我希望 AngularJS 代码在加载或重新加载/message路由时检查预先存在的auth.authenticated2值。 如果auth.authenticated2=false,则用户会收到一条消息,指出他们已注销。 但如果auth.authenticated2=true,我希望用户能够在/message路由上看到安全内容。 我不希望auth.authenticated2在重新加载路线时自动重新设置为false,就像现在一样。

下面是 message.html 中的代码,其中包含/message路由的 GUI 元素:

<div ng-show="authenticated2()">
    <h1>Secure Content</h1>
    <div>
        <p>Secure content served up from the server using REST apis for authenticated users.</p>
    </div>
</div>
<div ng-show="!authenticated2()">
    <h1>You are not logged in.</h1>
</div>

下面是message.js中的代码,它是管理/message路由的message模块的控制器:

angular.module('message', ['auth']).controller('message', function($scope, $http, $sce, auth) {
    $scope.authenticated2 = function() {
        return auth.authenticated2;
    }
    //Other code calling REST apis from the server omitted here to stay on topic
});

下面是 navigation 模块的代码,该模块也注入了 auth 服务:

angular.module('navigation', ['ngRoute', 'auth']).controller('navigation', function($scope, $route, auth, $http, $routeParams, $location) {
    $scope.credentials = {};//from old navigation module
    $scope.leadresult = "blank";
    $scope.processStep = "start";
    $scope.uname = "blank";
    $scope.wleadid = "initial blank value";
    $scope.existing = "blank";
    $scope.tab = function(route) {
        return $route.current && route === $route.current.controller;
    };
    $scope.authenticated1 = function() {
        return auth.authenticated1;
    }
    $scope.authenticated2 = function() {
        return auth.authenticated2;
    }
    $scope.login = function() {
        auth.authenticate1($scope.credentials, function(authenticated1) {
            //a bunch of stuff that does level 1 authentication, which is not relevant here
        })
    }
    $scope.logout = auth.clear;
    //some other methods to manage registration forms in a user registration process, which are omitted here because they are off-topic
    $scope.pinForm = function(isValid) {//this method finishes authentication of user at login
        if (isValid) {
            $scope.resultmessage.webleadid = $scope.wleadid;
            $scope.resultmessage.name = $scope.uname;
            $scope.resultmessage.existing = $scope.existing;
            var funcJSON = $scope.resultmessage;        
            auth.authenticate2(funcJSON, function(authenticated2) {
                if (authenticated2) {
                    $location.path('/message');
                    $scope.$apply();//this line successfully re-directs user to `/message` route LOGGED IN with valid credentials
                }
            });
        }
    };
    $scope.$on('$viewContentLoaded', function() {
        //method that makes an unrelated call to a REST service for ANONYMOUS users
    });
});

以下是 auth.jsauth 服务的代码:

angular.module('auth', []).factory( 'auth', function($rootScope, $http, $location) {
    var auth = {
        authenticated1 : false,
        authenticated2 : false,
        usrname : '',
        loginPath : '/login',
        logoutPath : '/logout',
        homePath : '/message',
        path : $location.path(),
        authenticate1 : function(credentials, callback) {
            var headers = credentials && credentials.username ? {
                authorization : "Basic " + btoa(credentials.username + ":" + credentials.password)
            } : {};
            $http.get('user', {
                headers : headers
            }).success(function(data) {
                if (data.name) { auth.authenticated1 = true; } 
                else { auth.authenticated1 = false; }
                callback && callback(auth.authenticated1);
            }).error(function() {
                auth.authenticated1 = false;
                callback && callback(false);
            });
        },
        authenticate2 : function(funcJSON, callback) {
            $http.post('/check-pin', funcJSON).then(function(response) {
                if(response.data.content=='pinsuccess'){
                    auth.authenticated2=true;
                    callback && callback(auth.authenticated2);
                }else {
                    auth.authenticated2=false;
                    auth.authenticated2 = false;
                    callback && callback(false);
                }
            });
        },
        clear : function() {
            $location.path(auth.loginPath);
            auth.authenticated1 = false;
            auth.authenticated2 = false;
            $http.post(auth.logoutPath, {}).success(function() { console.log("Logout succeeded");
            }).error(function(data) { console.log("Logout failed"); });
        },
        init : function(homePath, loginPath, logoutPath) {
            auth.homePath = homePath;
            auth.loginPath = loginPath;
            auth.logoutPath = logoutPath;
        }
    };
    return auth;
});

routeProvider由应用的主js文件管理,该文件hello.js,如下所示:

angular.module('hello', [ 'ngRoute', 'auth', 'home', 'message', 'public1', 'navigation' ])
    .config(
        function($routeProvider, $httpProvider, $locationProvider) {
            $locationProvider.html5Mode(true);/* This line is one of 3 places where we set natural urls to remote the default # */
            $routeProvider.when('/', {
                templateUrl : 'js/home/home.html',
                controller : 'home'
            }).when('/message', {
                templateUrl : 'js/message/message.html',
                controller : 'message'
            }).when('/public1', {
                templateUrl : 'js/public1/public1.html',
                controller : 'public1'
            }).when('/register', {
                templateUrl : 'js/navigation/register.html',
                controller : 'navigation'
            }).otherwise('/');
            $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
        }).run(function(auth) {
            // Initialize auth module with the home page and login/logout path
            // respectively
            auth.init('/checkpin', '/login', '/logout');
        });

不是一个完整的答案,因为在这里要更改的确切代码。但足以让一些东西建造得很好。

不应在身份验证服务中仅显式使用布尔值。据我所知,在成功进行身份验证后,您没有使用从服务器接收的任何数据。因此,每当您刷新时,一切都会丢失。代码中没有任何内容可以从刷新中恢复。

理想情况下,您应该拥有令牌或 cookie 之类的东西。Cookie 将被保存,并且可以在刷新后恢复,因此在启动身份验证服务时,您可以检查该 Cookie 是否存在。

您还可以保存可用于访问 indexedDB 中的 API 或类似内容的令牌。正如我之前所说,在身份验证服务的启动期间,您必须检查该令牌是否存在。

如果需要更多信息,请检查 Oauth2。尽管 Oauth2 不是身份验证 API,而是授权 API,但您可以使用密码授予类型。了解如何构建一个可靠的系统。其他授权类型大多只关注OAuth的授权方面。

因为 OP 在这里要求代码,所以它是:

when creating_service:
  if exists(cookie) or exists(token) and valid(cookie) or valid(token):
     mark_service_as_logged_in()

如果伪代码比文字更好。