调用另一个资源后,向所有资源广播标头

时间:2017-01-10 23:14:17

标签: angularjs rest http-headers ngresource angularjs-rootscope

我构建了一个rest api,现在是时候用angular处理数据了。为此,我构建了一个服务来连接我的资源。

所以我:

angular.module("myServiceRest", ['ngResource'])

.factory("myService",  function ($rootScope, $resource) {



    var apiData = $resource(
        "/api", {},
        {
            "getContains": {method: 'GET', isArray: false, url: "/api/users/:userid/:yearid/:groupeid/:levelid", headers: $rootScope.headers},
            "getContain": {method: 'GET', isArray: false, url: "/api/Contains/:containid", headers: $rootScope.headers},

            "postAuthTokens": {method: 'POST', url: "/api/auth-tokens"}

        });

    return {
        getGroupesContenus: function (user_id, year_id, groupe_id, level_id) {
            return apiData.getContains({userid: user_id, yearid: year_id, groupeid: groupe_id, levelid: level_id});
        },
        getContain: function (contain_id) {
            return apiData.getContain({containid: contain_id});
        },

        postAuthTokens: function(userData) {
            apiData.postAuthTokens(userData, function (data) {
                console.log("success !");
                $rootScope.headers = {
                    "Content-Type": "application/json",
                    "Authorization": "Basic ZWRnYXJrYW1kZW06TkVXVE9O",
                    "Accept": "application/json",
                    "X-Auth-Token": data.value
                };
            }, function (error) {
                console.log(error.data);
            })

        }
    }
});

这里我有3个资源:

  • getContains:/ api / users /:userid /:yearid /:groupeid /:levelid
  • getContain:/ api / Contains /:containid
  • postAuthTokens:/ api / auth-tokens

要访问getContains和getContain(登录后),用户需要设置通过postAuthTokens检索的令牌(X-Auth-Token)。

基本上,当用户登录时,他调用POST资源postAuthTokens,并通过data.value检索他的令牌(存储在数据库中),并且必须在X-Auth-Token中设置该令牌才能继续。

为此,我创建了一个$ rootScope,当用户登录时,我立即设置:

$rootScope.headers = {
                "Content-Type": "application/json",
                "Authorization": "Basic ZWRnYXJrYW1kZW06TkVXVE9O",
                "Accept": "application/json",
                "X-Auth-Token": data.value //Set the user token
            };

但它根本不起作用。就像$ rootScope.headers在调用后验证代码后重新初始化一样,因为当用户登录后我在我的Chrome控制台中出现了这个错误:

angular.js:14328 Possibly unhandled rejection: {"data":{"error":{"code":500,"message":"Internal Server Error","exception":[{"message":"X-Auth-Token header is required","class":"Symfony\\Component\\Security\\Core\\Exception\\BadCredentialsException","trace":...

我的$ rootScope.headers根本没有设置。

那么在调用postAuthTokens之后如何将我的$ rootScope.headers广播到所有资源头?

1 个答案:

答案 0 :(得分:1)

不是将标头添加到根范围,而是将它们添加到$http服务:

$http.defaults.headers.common['X-Auth-Token'] = data.value

然后应将它们自动添加到所有后续HTTP请求中