如何通过对飞至$资源,angularjs头 [英] How to pass headers on the fly to $resource for angularjs

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

问题描述

现在,我知道动态为angularjs呼叫头设置令牌的唯一方法是通过 $ HTTP 像这样:

Right now, the only way that I know for setting tokens in headers dynamically for an angularjs call is via $http like so:

return $http.get({
  url: 'https://my.backend.com/api/jokes',
  params: {
    'jokeId': '5',
  },
  headers: {
    'Authorization': 'Bearer '+ $scope.myOAuthToken
  }
});

但我想弄清楚如何通过$资源通过这个,这里的一些伪code不工作:

But I want to figure out how to pass this via $resource, here's some pseudo-code that doesn't work:

...
.factory('myFactory',
  ['$resource',
    function($resource){
      return {
        jokes: $resource('https://my.backend.com/api/jokes', null, {
          query: {
            method: 'GET'
          }
        })
      };
    }
  ]
);
...
return myFactory.jokes.query({
  'jokeId': '5',
  'headers': {
    'Authorization': 'Bearer '+ $scope.myOAuthToken
  }
});

如何传递头在飞行至$资源,angularjs?

How can I pass headers on the fly to $resource for angularjs?

推荐答案

我不认为这是可以做到你想的样子,作为配置对象不可用的操作方法。但动作的配置方法有它。所以你可以做的是,而不是直接返回的资源,创建一个函数,它接受一个参数的身份验证令牌,然后构建资源并返回。

I don't think this can be done the way you are trying, as the config object is not available on action method. But the action config method has it. So what you can do is, rather than returning resource directly, create a function that takes a parameter the auth token and then construct the resource and return.

return {
    jokes: function (token) {
        return $resource('https://my.backend.com/api/jokes', null, {
            query: {
                method: 'GET'
                headers: {
                    'Authorization': 'Bearer ' + token
                }
            }
        })
    }
};

然后调用服务功能为

Then call the service function as

myFactory.jokes($scope.myOAuthToken).query({'jokeId': '5'});

这篇关于如何通过对飞至$资源,angularjs头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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