如何在angularjs中更改资源的标头

时间:2014-03-11 17:51:45

标签: javascript angularjs http-headers

我正在尝试设置资源的标头(代码如下)。 碰巧的是,当我实例化我的资源($scope.user = new rsrUser;)时,angularjs会获取尚未定义的cookie(从“getHMAC()”内部触发“未定义”错误)。只有在触发“$ scope.login()”时才会定义cookie(当用户单击界面中的按钮时会发生cookie)。

有更好的方法吗?

controllers.js

angularjsWebInterfaceControllers.controller('loginCtrl', ['$scope', 'rsrUser',
function($scope, rsrUser){
    $cookieStore.put("username","therebedragons");
    $cookieStore.put("password","therebedragons");

    $scope.user = new rsrUser;
    $scope.user.username = ""; //bound to input field in interface
    $scope.user.password = ""; //bound to input field in interface


    $scope.login = function() {
      $cookieStore.put("username", $scope.user.username);
      $cookieStore.put("password", $scope.user.password);
      $cookieStore.put("state", "loggedOUT");

      $scope.user.$logIn(
        function(){
           $cookieStore.put("state", "loggedIN");
        }, function() {
          $cookieStore.put("username","therebedragons");
          $cookieStore.put("password","therebedragons");
          $cookieStore.put("state", "loggedOUT");
        }
      )
     };
}]);

services.js

angularjsWebInterfaceServices.service('rsrUser', [ '$resource', '$cookieStore',
  function($resource, $cookieStore){
    var req = "/login"
    var timestamp = getMicrotime(true).toString();
    var username = $cookieStore.get("username");
    var key = $cookieStore.get("password");
    return $resource(baseURL + req, {}, {
      logIn: {method:'POST',
              isArray:false,
              headers:{
                  'X-MICROTIME': timestamp,
                  'X-USERNAME': username,
                  'X-HASH': getHMAC(username,timestamp,req,key)
                }
            }
    });
  }]);

编辑:实际上,一旦控制器被实例化,cookie就会被取消;

1 个答案:

答案 0 :(得分:2)

标头的值可以是返回字符串的函数(请参阅此处的参数:http://docs.angularjs.org/api/ng/service/$http#usage)。这样,在调用logIn方法之前,不会在您的资源中访问cookie。

return $resource(baseURL + req, {}, {
  logIn: {method:'POST',
          isArray:false,
          headers: {
              'X-MICROTIME': timestamp,
              'X-USERNAME': function() {
                return $cookieStore.get("username");
              },
              'X-HASH': function() {
                var username = $cookieStore.get("username");
                return getHMAC(username,timestamp,req,key)
              }
            }
        }
});