4

$resource とリクエスト ラッパーを使用して REST クライアントを作成しようとしています。以下のコードを見ることができます。すべて正常に動作しますが、問題があります。

RequestWrapper モジュールは、(フラグメント URI から) アクセス トークンを設定するために使用されます。必要なのは、アクセス トークンが requestWrapper.set() 関数から設定されるまで、可能なリクエストをブロックできるようにすることです。

resources.factory('RequestWrapper', ['$http', '$q', function($http, $q) {
  var scope;
  var requestWrapper = {};
  var deferred = $q.defer();

  // get info about the token
  requestWrapper.get = function() { return scope; };

  // Set the info related to the token
  requestWrapper.set = function(newScope) {
    scope = newScope;
    $http.defaults.headers.common['Authorization'] = 'Bearer ' + scope.token.access_token;

    // Here I resolve the promise
    deferred.resolve(true);
  };

  requestWrapper.wrap = function(resource, actions) {
    var wrappedResource = resource;
    for (var i=0; i < actions.length; i++) { request(wrappedResource, actions[i]); };
    return wrappedResource;
  };

  var request = function(resource, action) {

    resource['_' + action]  = resource[action];

    resource[action] = function(param, data, success, error) {
      if (scope && scope.token.expires_at < new Date()) {
        window.location.replace(scope.endpoint)
      } else {
        return resource['_' + action](param, data, success, error);
      }
    };
  };

  return requestWrapper;
}]);

// Example on using the Request Wrapper
resources.factory('Profile', ['RequestWrapper', '$resource', function(RequestWrapper, $resource) {
  var resource = $resource(endpoint + '/me');
  return RequestWrapper.wrap(resource, ['get']);
}]);

私は約束を使用しようとしましたが (私は専門家ではありません)、その背後で動作するロジックを取得しました。モジュールの初期化中に定義し、アクセストークンが定義された後に解決します。ここで、私の主な関心事は、promise.then() メソッドをどこに配置して、トークンが設定されている場合にのみリクエストを開始できるかを理解することです。

deferred.promise.then(function() { ... })

ラッパー関数やその他の場所に配置しようとしましたresource['_' + action](param, data, success, error)が、ブラインドのように感じます。

お時間をいただきありがとうございます。

4

1 に答える 1

0

セッションサービスを使用してトークンを提供し、他のコントローラーで$scope.token後続のアクションをトリガーしないのはなぜですか?$scope.$watch('token', ...)

AngularJS ドキュメントのページを読むことをお勧めします$http。それでもリクエストを「ブロック」したい場合は、インターセプターを使用できます ( http://code.angularjs.org/1.1.5/docs/api/ng.$を参照)。 http )。

于 2013-06-26T22:36:22.873 に答える