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

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

问题描述

我想送请求从我的API资源时的身份验证令牌。

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

我没有使用$资源实现服务:

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 标记每个请求通过待办事项服务发送。我可以通过把它变成具体行动的号召,发送。比如这个作品:

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()} );

不过,我想preFER定义的access_token如参数藤堂服务,因为它要与每一个电话发送。并改善干燥。
但是,一切都在工厂只执行一次,这样的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.

有没有把一个动态更新请求参数在服务的方式?

推荐答案

感谢安迪·乔斯林。我拿起他的包资源行动的想法。该资源的服务会是现在这个样子:

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;
}])

正如你所看到的资源是指在首位的常用方法。在我的例子,这包括所谓的更新自定义操作。之后的资源是由占有资源和行动作为参数数组中的 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.

正如你所期望后者的方法实际上包装的行动,包括在每个请求的身份验证令牌,并返回修改后的资源。因此,让我们来看看code为:

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()方法创建一个从它的参数资源的副本,并通过循环动作数组调用另一个函数 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 方法首先是创造了preexisting资源操作的副本。此副本有一个结尾下划线。因此,查询()变成 _query()。之后一个新的方法将覆盖原来的查询()方法。这种新的方法包装 _query(),安迪·乔斯林的建议,为每个请求的身份验证令牌通过该行动派。

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资源(获取,查询,保存等)predefined行动,而无需重新定义它们。而在code的其余部分(控制器,例如内),我们可以使用默认的动作名称。

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:如何发送身份验证令牌与$资源请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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