0

我正在使用 angular-local-storage 将身份验证信息存储在服务中。但是,当我尝试从拦截器访问相同的内容时,它返回 null。我已经展示了下面的代码。

应用程序.js

angular.module('Spis', ['ui.router', 'ngRoute', 'LocalStorageModule', 'angular-loading-bar', 'oc.lazyLoad'])

.config(['$stateProvider', '$urlRouterProvider', '$ocLazyLoadProvider', function ($stateProvider, $urlRouterProvider, $httpProvider, $ocLazyLoadProvider) {

$urlRouterProvider.otherwise("/home");

$stateProvider
    .state("home", {
        url: '/home',
        templateUrl: '/app/views/home.html',
        controller: 'homeController',
        resolve: {
            deps: ['$ocLazyLoad', function ($ocLazyLoad) {
                return $ocLazyLoad.load({
                    insertBefore: '#ng_load_plugins_before', // load the above css files before a LINK element with this ID. Dynamic CSS files must be loaded between core and theme css files
                    files: [
                        'app/controllers/homeController.js'
                    ]
                });
            }]
        }
    })
    .state("login", {
        url: '/login',
        templateUrl: 'app/views/login.html',
        controller: 'loginController',
        resolve: {
            deps: ['$ocLazyLoad', function ($ocLazyLoad) {
                return $ocLazyLoad.load({
                    insertBefore: '#ng_load_plugins_before', // load the above css files before a LINK element with this ID. Dynamic CSS files must be loaded between core and theme css files
                    files: [
                        'app/controllers/loginController.js'
                    ]
                });
            }]
        }
    })
}])

.config(['$qProvider', function ($qProvider) {
$qProvider.errorOnUnhandledRejections(false);
}])

.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('authInterceptorService');
}])

.run(["$rootScope", "$state", 'authService', function ($rootScope, $state, authService) {
$rootScope.$state = $state; // state to be accessed from view
authService.fillAuthData();
}]);

登录控制器.js

'use strict';
angular.module('Spis').controller('loginController', ['$scope', '$location', '$state', 'authService', function ($scope, $location, $state, authService) {

$scope.loginData = {
    userName: "",
    password: ""
};

$scope.message = "";

$scope.login = function (isValid) {
    if (isValid) {
        authService.login($scope.loginData).then(function (response) {
            console.log(authService.authentication);
            $state.go('school');
    },
     function (err) {
         $scope.message = err.error_description;
     });
    }
};

}]);

authService.js

'use strict';
angular.module('Spis').factory('authService', ['$http', '$q', 'localStorageService', function ($http, $q, localStorageService) {

var serviceBase = 'http://localhost:12258/';
var authServiceFactory = {};

var _authentication = {
    isAuth: false,
    userName: ""
};

var _login = function (loginData) {

    var data = "grant_type=password&username=" + loginData.userName + "&password=" + loginData.password;

    var deferred = $q.defer();

    $http.post(serviceBase + 'token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } })
        .then(function (response) {
            localStorageService.set('authorizationData', {
                token: response.data.access_token,
                userName: loginData.userName
            });

            _authentication.isAuth = true;
            _authentication.userName = loginData.userName;

            console.log(localStorageService.get('authorizationData'));
            deferred.resolve(response);
        })

        .then(function (err, status) {
            _logOut();
            deferred.reject(err);
        });

    return deferred.promise;

};
var _fillAuthData = function () {

    var authData = localStorageService.get('authorizationData');
    console.log(authData);
    if (authData) {
        _authentication.isAuth = true;
        _authentication.userName = authData.userName;
    }
}

authServiceFactory.saveRegistration = _saveRegistration;
authServiceFactory.login = _login;
authServiceFactory.logOut = _logOut;
authServiceFactory.fillAuthData = _fillAuthData;
authServiceFactory.authentication = _authentication;

return authServiceFactory;
}]);

authInterceptorService.js

'use strict';
angular.module('Spis').factory('authInterceptorService', ['$q', '$location', 'localStorageService', function ($q, $location, localStorageService) {

var authInterceptorServiceFactory = {};

var _request = function (config) {        

    config.headers = config.headers || {};

    var lsKeys = localStorageService.keys();
    var authData = localStorageService.get('authorizationData');
    console.log(authData);
    if (authData) {
        config.headers.Authorization = 'Bearer ' + authData.token;
    }

    return config;
}

authInterceptorServiceFactory.request = _request;

return authInterceptorServiceFactory;
}]);

authInterceptor 服务中的身份验证数据始终为空。关于什么是错的任何想法?

4

1 回答 1

0

也发生在我身上,但它适用于本机 javascript localStorage。 https://www.w3schools.com/jsref/prop_win_localstorage.asp

于 2018-06-26T14:49:26.540 回答