AngularJS:如何使用 $resource 请求发送身份验证令牌? [英] AngularJS: How to send auth token with $resource requests?

查看:23
本文介绍了AngularJS:如何使用 $resource 请求发送身份验证令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在从我的 API 请求资源时发送一个身份验证令牌.

I want to send an auth token when requesting a resource from my API.

我确实使用 $resource 实现了一个服务:

I did implement a service using $resource:

factory('Todo', ['$resource', function($resource) {
 return $resource('http://localhost:port/todos.json', {port:":3001"} , {
   query: {method: 'GET', isArray: true}
 });
}])

而且我有一个存储身份验证令牌的服务:

And I have a service that stores the auth token:

factory('TokenHandler', function() {
  var tokenHandler = {};
  var token = "none";

  tokenHandler.set = function( newToken ) {
    token = newToken;
  };
  tokenHandler.get = function() {
    return token;
  };

  return tokenHandler;
});

我想从 tokenHandler.get 发送令牌,并通过 Todo 服务发送每个请求.我能够通过将其放入特定操作的调用中来发送它.例如这有效:

I would like to send the token from tokenHandler.get with every request send via the Todo service. I was able to send it by putting it into the call of a specific action. For example this works:

Todo.query( {access_token : tokenHandler.get()} );

但我更愿意将 access_token 定义为 Todo 服务中的一个参数,因为它必须在每次调用时发送.并改善DRY.但是工厂中的所有东西都只执行一次,所以在定义工厂之前,access_token 必须可用,之后不能更改.

But I would prefer to define the access_token as a parameter in the Todo service, as it has to be sent with every call. And to improve DRY. But everything in the factory is executed only once, so the access_token would have to be available before defining the factory and it cant change afterwards.

有没有办法在服务中放置一个动态更新的请求参数?

推荐答案

感谢 Andy Joslin.我选择了他包装资源操作的想法.资源的服务现在看起来像这样:

Thanks to Andy Joslin. I picked his idea of wrapping the resource actions. The service for the resource looks like this now:

.factory('Todo', ['$resource', 'TokenHandler', function($resource, tokenHandler) {
  var resource = $resource('http://localhost:port/todos/:id', {
    port:":3001",
    id:'@id'
    }, {
      update: {method: 'PUT'}
    });

  resource = tokenHandler.wrapActions( resource, ["query", "update"] );

  return resource;
}])

如您所见,资源首先以通常的方式定义.在我的示例中,这包括一个名为 update 的自定义操作.之后,资源被 tokenHandler.wrapAction() 方法的返回覆盖,该方法将资源和一组动作作为参数.

As you can see the resource is defined the usual way in the first place. In my example this includes a custom action called update. Afterwards the resource is overwritten by the return of the tokenHandler.wrapAction() method which takes the resource and an array of actions as parameters.

正如您所期望的那样,后一种方法实际上包装了操作以在每个请求中包含身份验证令牌并返回修改后的资源.那么让我们来看看它的代码:

As you would expect the latter method actually wraps the actions to include the auth token in every request and returns a modified resource. So let's have a look at the code for that:

.factory('TokenHandler', function() {
  var tokenHandler = {};
  var token = "none";

  tokenHandler.set = function( newToken ) {
    token = newToken;
  };

  tokenHandler.get = function() {
    return token;
  };

  // wrap given actions of a resource to send auth token with every
  // request
  tokenHandler.wrapActions = function( resource, actions ) {
    // copy original resource
    var wrappedResource = resource;
    for (var i=0; i < actions.length; i++) {
      tokenWrapper( wrappedResource, actions[i] );
    };
    // return modified copy of resource
    return wrappedResource;
  };

  // wraps resource action to send request with auth token
  var tokenWrapper = function( resource, action ) {
    // copy original action
    resource['_' + action]  = resource[action];
    // create new action wrapping the original and sending token
    resource[action] = function( data, success, error){
      return resource['_' + action](
        angular.extend({}, data || {}, {access_token: tokenHandler.get()}),
        success,
        error
      );
    };
  };

  return tokenHandler;
});

如您所见,wrapActions() 方法根据资源的参数创建资源的副本,并循环遍历 actions 数组以调用另一个函数 tokenWrapper() 用于每个动作.最后它返回资源的修改副本.

As you can see the wrapActions() method creates a copy of the resource from it's parameters and loops through the actions array to call another function tokenWrapper() for every action. In the end it returns the modified copy of the resource.

tokenWrapper 方法首先创建一个预先存在的资源操作的副本.此副本有一个尾随下划线.所以query()变成了_query().之后一个新方法覆盖了原来的 query() 方法.这个新方法包装了 _query(),正如 Andy Joslin 所建议的那样,为通过该操作发送的每个请求提供身份验证令牌.

The tokenWrappermethod first of all creates a copy of preexisting resource action. This copy has a trailing underscore. So query()becomes _query(). Afterwards a new method overwrites the original query() method. This new method wraps _query(), as suggested by Andy Joslin, to provide the auth token with every request send through that action.

这种方法的好处是,我们仍然可以使用每个 angularjs 资源(获取、查询、保存等)附带的预定义操作,而无需重新定义它们.在其余代码中(例如在控制器中),我们可以使用默认操作名称.

The good thing with this approach is, that we still can use the predefined actions which come with every angularjs resource (get, query, save, etc.), without having to redefine them. And in the rest of the code (within controllers for example) we can use the default action name.

这篇关于AngularJS:如何使用 $resource 请求发送身份验证令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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