使用从服务器获取的值配置角度$ http

时间:2015-08-05 10:20:30

标签: angularjs session angular-http-interceptors

我正在构建我的(第一个)角度应用,它会将标记插入标题中(显示的内容大部分来自here

angular.module('对myApp&#39)

.factory('sessionInjector', ['SessionService', function(SessionService) {  
   var sessionInjector = {
        request: function(config) {
            config.headers['x-session-token'] = SessionService.getToken();
            return config;
        }
    };
    return sessionInjector;
}])

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

我遇到的问题是SessionService - 如何通过调用服务器来初始化它?

例如,这没有用:

.factory('SessionService', ['$injector', function($injector){
    var token = "";

    return {
        getToken: function () {
            var http = $injector.get('$http');
            if (token === "") {
                http.get('http://localhost/api/auth/getToken').success(function (ret) {
                    token = ret;
                });
            }
            return token; 
            //I can see a $q/deferred/promise should be used somehow here... 
            //but I'm not sure it solves the problem I'm having...
        }
    }
}]);

因为它只是将我的CPU重载为100%...

因为它是我的第一个有角度的应用程序,我确定我错过了什么,但是......什么?

修改
对此事的另一种看法......虽然仍然无法工作......(再次,耗尽cpu,可能是无限循环)

  .factory('sessionData', function () {
    var currentToken = '[uninitialized-token]';

    return {
        getToken: function () {
            return currentToken;
        },
        setToken: function (token) {
            currentToken = token;
        }
    }
})

.factory('sessionInjector', ['sessionData', '$injector', '$q', function (sessionData, $injector, $q) {
    var sessionInjector = {
        request: function (config) {
            var deferred = $q.defer();
            var http = $injector.get('$http');
            http.get('http://localhost/api/auth/getToken').success(function (ret) {
                sessionData.setToken(ret);
                console.log("successfully authenticated with token " + sessionData.getToken());
                config.headers['x-header-sessionID'] = sessionData.getToken();
                deferred.resolve(config);
            })
            .error(function(){
                console.log("failed to authenticate");
                deferred.resolve(config);
            });

            return deferred.promise;
        }
    };
    return sessionInjector;
}])

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

.run(['$http', 'sessionData', function ($http, configs, sessionData) {
    $http.get('http://localhost/api/auth/testMethod').then(function (ret) {
        //do something...
    });
}])

2 个答案:

答案 0 :(得分:1)

检查此修改后的代码片段是否能解决您的问题。

.factory('SessionService', ['$http', '$q', function($http, $q) {
    var token = null;
    var sessionService = {};
    var differred = $q.defer();

    sessionService.readToken = function() {
        return $http.get('http://localhost/api/auth/getToken')
            .success(function (res) {
                console.log('Auth Success and token received: ' + JSON.stringify(res.data));

                // Extract the token details from the received JSON object
                token = res.data;
                differred.resolve(res);
            }, function (res) {
                console.log('Error occurred : ' + JSON.stringify(res));
                differred.reject(res);
            }
        )
    };

    sessionService.getToken = function() {
        return token;
    };

    sessionService.isAnonymous = function() {
        if (token)
            return true;
        else
            return false;
    };

    return sessionService;
}])


.factory('sessionInjector', ['SessionService', function(SessionService) {
    var sessionInjector = {
        request: function(config) {
            if (!sessionService.isAnonymous) {
                config.headers['x-session-token'] = SessionService.getToken();
                return config;
            }
        }
    };
    return sessionInjector;
}])

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

答案 1 :(得分:0)

答案实际上非常简单 - 如果目标网址是用于登录,则不要注入任何内容(查找评论the fix):

.factory('sessionData', function () {
    var currentToken = '[uninitialized-token]';

    return {
        getToken: function () {
            return currentToken;
        },
        setToken: function (token) {
            currentToken = token;
        }
    }
})

.factory('sessionInjector', ['sessionData', '$injector', '$q', function (sessionData, $injector, $q) {
    var sessionInjector = {
        request: function (config) {

            //The fix:
            if(config.url === 'http://localhost/api/auth/getToken')
                return config;

            var deferred = $q.defer();
            var http = $injector.get('$http');
            http.get('http://localhost/api/auth/getToken').success(function (ret) {
                sessionData.setToken(ret);
                console.log("successfully authenticated with token " + sessionData.getToken());
                config.headers['x-header-sessionID'] = sessionData.getToken();
                deferred.resolve(config);
            })
            .error(function(){
                console.log("failed to authenticate");
                deferred.resolve(config);
            });

            return deferred.promise;
        }
    };
    return sessionInjector;
}])

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

.run(['$http', 'sessionData', function ($http, configs, sessionData) {
    $http.get('http://localhost/api/auth/testMethod').then(function (ret) {
        //do something...
    });
}])