Provide default parameters automatically with $resource?

前端 未结 1 1533
独厮守ぢ
独厮守ぢ 2021-01-21 10:33

I\'m creating a simple AngularJS app that uses Alfresco as back-end over the provided REST API.

Firstly, authentication is performed through the appropriate service whic

1条回答
  •  迷失自我
    2021-01-21 11:26

    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

    0 讨论(0)
提交回复
热议问题