Dynamic Resource Headers

后端 未结 2 1459
走了就别回头了
走了就别回头了 2020-12-14 11:11

I would like to have service providing a resource as in the following code:

   angular.module(\'myApp.userService\',         


        
2条回答
  •  不思量自难忘°
    2020-12-14 11:55

    Starting from angularjs v1.1.1 and ngResource v.1.1.1 this is possible to accomplish using the headers property of the $resource action object.

    You may wrap your resource in a function which accepts custom headers as a parameter and returns a $resource object with your custom headers set at the appropriate action definitions:

    PLUNKER

    var app = angular.module('plunker', ['ngResource']);
    
    app.controller('AppController',
      [
        '$scope',
        'UserService',
        function($scope, UserService) {
          $scope.user = {login: 'doe@example.com', password: '123'};
    
          $scope.connect = function() {
            // dropping out base64 encoding here, for simplicity
            var hash = 'Basic ' + $scope.user.login + ':' + $scope.user.password;
            $scope.user.headers = [{Authorization: hash}];
    
            UserService({Authorization: hash}).connect(
              function () {
                $location.url('/connected');
              },
              function () {
                console.log('There was an error, please try again');
              }
            );
    
          };
    
        }
      ]
    );
    
    app.factory('UserService', function ($resource) {
      return function(customHeaders){
        return $resource('/api/user', {}, {
          connect: { 
            method: 'POST',
            params: {},
            isArray: false,
            headers: customHeaders || {}
          }
        });
      };
    
    });
    

提交回复
热议问题