3

このコードが何をするのか一般的に説明していただけますか?

App.config(['$httpProvider', function ($httpProvider) {
  $httpProvider.responseInterceptors.push('HttpSpinnerInterceptor');
  $httpProvider.defaults.transformRequest.push(function (data, headersGetter) {
    angular.element('.brand img').attr("src","<%= asset_path('brand/brand.gif') %>");
    return data;
  });
}]);

App.factory('HttpSpinnerInterceptor', function ($q, $window) {
  return function (promise) {
    return promise.then(function (response) {
      angular.element('.brand img').attr("src","<%= asset_path('brand/brand.png') %>");
      return response;
    }, function (response) {
      angular.element('.brand img').attr("src","<%= asset_path('brand/brand.png') %>");
      return $q.reject(response);
    });
  };
});

それがいくつかの応答を傍受し、画像のsrc属性を挿入するといういくつかの推測を除いて、私は完全に理解していません。

HttpSpinnerInterceptorがいつどのように呼び出され、「promise」パラメーターが何であるかがわかりません。

4

1 に答える 1

5
  1. HttpSpinnerInterceptorは、$httpサービスを使用して発行された各要求が完了した後(成功したかどうかに関係なく)、promiseが呼び出し元に解決される前に呼び出されます(結果を延期できます)。実際には、変換要求は必要ありません。これは、HttpSpinnerInterceptorとほとんど同じであるため(またはHttpSpinnerInterceptorは必要ありません...)、何も変換しないためです。

  2. promiseパラメータは、$q後で再販できるため、リクエストの結果を使用して非同期アクションを実行する必要がある場合に使用できるPromiseであるため、呼び出し元は後で結果を取得します。実際、コードでは、画像のsrc属性を変更して、この約束を直接解決(または拒否)します。

ドキュメントへのリンクは次のとおりです。

  1. $httpサービスの使用: http ://docs.angularjs.org/api/ng.$http-「レスポンスインターセプター」と「リクエストとレスポンスの変換」を注意深く見てください
  2. AngularJSの約束:http://docs.angularjs.org/api/ng.$q
于 2013-01-31T15:35:13.630 に答える