Provide default parameters automatically with $resource?

有些话、适合烂在心里 提交于 2019-12-02 00:59:49

Use an $http interceptor.

Create a factory function which reconfigures the request for any URL, adding the auth token to the parameters only if it is set:

app.factory('httpRequestInterceptor', function (Auth) {
  return {
    request: function (config) {
      if (Auth.token) {
        config.url =  URI(config.url).addSearch({'_auth_token':Auth.token}).toString();
      }
      return config;
    }
  };
})

(Note that I am using URI.js to add the parameters, since I patterned my answer after this blog post, where the author uses it as well)

Pass $httpProvider into your config block, and push the name string of your interceptor service into its interceptor array:

.config(function ($httpProvider) {
  $httpProvider.interceptors.push('httpRequestInterceptor');
})

Any $http requests (including those wrapped by $resource) will be intercepted and modified, if appropriate, before the browser executes them.

Plunker Demo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!