动态资源头 [英] Dynamic Resource Headers

查看:26
本文介绍了动态资源头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望服务提供如下代码所示的资源:

I would like to have service providing a resource as in the following code:

   angular.module('myApp.userService', ['ngResource'])
  .factory('UserService', function ($resource)
  {
    var user = $resource('/api/user', {},
          {
            connect: { method: 'POST', params: {}, isArray:false }
          });
    return user;
  }

然后在使用 connect 操作时,我想动态传递一个 HTTP 标头,这意味着它可能会因每次调用而改变.这是一个例子,在控制器中,请看代码中的注释:

Then when using the connect action, I would like to dynamically pass a HTTP header, meaning that it may change for each call. Here is an example, in the controller, please see the comment in the code :

 $scope.user = UserService;

 $scope.connect = function ( user )
        {
          var hash = 'Basic ' + Base64Service.encode(user.login + ':' + user.password);

          // I would like this header to be computed 
          // and used by the user resource
          //  each time I call this function
          $scope.user.headers = [{Authorization: hash}];

          $scope.user.connect( {},
              function()
              {
                  // successful login
                  $location.path('/connected');
              }
              ,function()
              {
                  console.log('There was an error, please try again');
              });
       }

您知道直接或通过技巧来做到这一点的方法吗?

Do you know a way to do that, either directly or via a trick?

接受的答案不能完全回答问题,因为标头不是完全动态的,因为工厂实际上返回了一个工厂(!),这在我的代码中并非如此.

Accepted answer does not fully answer the question as the headers are not totally dynamic because the factory returns actually a factory (!) which is not the case in my code.

由于 $resource 是一个工厂,因此无法使其动态化.

As $resource is a factory, there is no way to make it dynamic.

每次用户连接时,我最终都会销毁资源对象.这样,我就可以在用户连接时计算带有标头的资源.

I finally destroy the resource object each time the user connects. This way, I have the resource with a header computed when the user connects.

@Stewie 提供的解决方案对此很有用,因此我将其保留为已接受.

The solution provided by @Stewie is useful for that, so I keep it as accepted.

这是我进行连接的方式,当(重新)连接时资源被破坏/重新创建,它可以多次使用:

Here is how I did the connect, which can be used multiple times as the resource is destroyed/recreated when (re)connecting:

 this.connect = function (user)
 {
    self.hash = 'Basic ' + Base64Service.encode(user.login + ':' + user.password);
console.log("CONNECT login:" + user.login + " - pwd:" + user.password + " - hash:" + self.hash);

if (self.userResource)
{
  delete self.userResource;
}

self.userResource = $resource('/api/user/login', {}, {
  connect: {
    method: 'POST',
    params: {},
    isArray: false,
    headers: { Authorization: self.hash }
  }
});

var deferred = $q.defer();
self.userResource.connect(user,
  function (data)
  {
    //console.log('--------- user logged in ----- ' + JSON.stringify(data));
    // successful login
    if (!!self.user)
    {
      angular.copy(data, self.user);
    }
    else
    {
      self.user = data;
    }

    self.setConnected();

    storage.set('user', self);

    deferred.resolve(self);
  },
  function (error)
  {
    self.user = {};
    self.isLogged = false;

    storage.set('user', self);

    deferred.reject(error);
  }
);

return deferred.promise;

};

推荐答案

从 angularjs v1.1.1 和 ngResource v.1.1.1 开始,这可以使用 headers 属性来完成>$resource 动作对象.

Starting from angularjs v1.1.1 and ngResource v.1.1.1 this is possible to accomplish using the headers property of the $resource action object.

您可以将您的资源包装在一个函数中,该函数接受自定义标头作为参数并返回一个 $resource 对象,并在适当的操作定义中设置您的自定义标头:

You may wrap your resource in a function which accepts custom headers as a parameter and returns a $resource object with your custom headers set at the appropriate action definitions:

PLUNKER

var app = angular.module('plunker', ['ngResource']);

app.controller('AppController',
  [
    '$scope',
    'UserService',
    function($scope, UserService) {
      $scope.user = {login: 'doe@example.com', password: '123'};

      $scope.connect = function() {
        // dropping out base64 encoding here, for simplicity
        var hash = 'Basic ' + $scope.user.login + ':' + $scope.user.password;
        $scope.user.headers = [{Authorization: hash}];

        UserService({Authorization: hash}).connect(
          function () {
            $location.url('/connected');
          },
          function () {
            console.log('There was an error, please try again');
          }
        );

      };

    }
  ]
);

app.factory('UserService', function ($resource) {
  return function(customHeaders){
    return $resource('/api/user', {}, {
      connect: { 
        method: 'POST',
        params: {},
        isArray: false,
        headers: customHeaders || {}
      }
    });
  };

});

这篇关于动态资源头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆