动态资源标题 [英] Dynamic Resource Headers

查看:137
本文介绍了动态资源标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有服务提供的资源,如以下code:

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

   angular.module('myApp.userService', ['ngResource'])
  .factory('UserService', function ($resource)
  {
    var user = $resource('/api/user', {},
          {
            connect: { method: 'POST', params: {}, isArray:false }
          });
    return user;
  }

然后使用连接操作时,我想动态传递HTTP头,这意味着它可以为每个来电更改。这里有一个例子,在控制器,请在code注释:

Then when using the connect action, I would like to dynamically pass a HTTP header, meaning that it may change for each call. Here is an example, in the controller, please see the comment in the code :

 $scope.user = UserService;

 $scope.connect = function ( user )
        {
          var hash = 'Basic ' + Base64Service.encode(user.login + ':' + user.password);

          // I would like this header to be computed 
          // and used by the user resource
          //  each time I call this function
          $scope.user.headers = [{Authorization: hash}];

          $scope.user.connect( {},
              function()
              {
                  // successful login
                  $location.path('/connected');
              }
              ,function()
              {
                  console.log('There was an error, please try again');
              });
       }

你知道的方式来做到这一点,无论是直接或通过一个把戏?

Do you know a way to do that, either directly or via a trick?

接受的答案并不完全回答这个问题的头是不是完全动态的,因为工厂的实际返回工厂(!),这是不是在我的code的情况。

Accepted answer does not fully answer the question as the headers are not totally dynamic because the factory returns actually a factory (!) which is not the case in my code.

由于$资源是一个工厂,有没有办法让它充满活力。

As $resource is a factory, there is no way to make it dynamic.

我终于在用户每次连接时销毁资源对象。这样一来,我有当用户将计算的报头的资源。

I finally destroy the resource object each time the user connects. This way, I have the resource with a header computed when the user connects.

由@Stewie提供的解决方案是有用的,所以我把它作为接受。

The solution provided by @Stewie is useful for that, so I keep it as accepted.

下面是我做了连接,可多次使用的资源被销毁/重建时(重新)连接:

Here is how I did the connect, which can be used multiple times as the resource is destroyed/recreated when (re)connecting:

 this.connect = function (user)
 {
    self.hash = 'Basic ' + Base64Service.encode(user.login + ':' + user.password);
console.log("CONNECT login:" + user.login + " - pwd:" + user.password + " - hash:" + self.hash);

if (self.userResource)
{
  delete self.userResource;
}

self.userResource = $resource('/api/user/login', {}, {
  connect: {
    method: 'POST',
    params: {},
    isArray: false,
    headers: { Authorization: self.hash }
  }
});

var deferred = $q.defer();
self.userResource.connect(user,
  function (data)
  {
    //console.log('--------- user logged in ----- ' + JSON.stringify(data));
    // successful login
    if (!!self.user)
    {
      angular.copy(data, self.user);
    }
    else
    {
      self.user = data;
    }

    self.setConnected();

    storage.set('user', self);

    deferred.resolve(self);
  },
  function (error)
  {
    self.user = {};
    self.isLogged = false;

    storage.set('user', self);

    deferred.reject(error);
  }
);

return deferred.promise;

};

推荐答案

这angularjs V1.1.1和ngResource v.1.1.1这是可能使用来完成启动标题 $资源属性操作对象。

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 || {}
      }
    });
  };

});

这篇关于动态资源标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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