Dynamic Resource Headers

后端 未结 2 1457
走了就别回头了
走了就别回头了 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:47

    I set my Services up a little differently.

    angular.module('MyApp').factory('UserService',function($resource, localStorageService) {
    
        var userResource = function(headers) {
            return $resource("api/user", {},
                {
                    get: {
                        method: 'GET',
                        headers: headers
                    },
    
                    create: {
                        method: 'POST',
                        headers: headers
                    }
                }
            );
        };
    
        return {
    
            api: userResource,
    
            get: function(userid){
                var service = this;
                return service.api({"token": "SomeToken"}).get({userid: userid}, function (data){
                    return data;
                });
            },
    
            create: function(user){
                var service = this;
                return service.api({"token": localStorageService.get("token")}).create({user: user}, function (data){
                    return data;
                });
            }
    
        };
    
    });
    
    0 讨论(0)
  • 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 || {}
          }
        });
      };
    
    });
    
    0 讨论(0)
提交回复
热议问题