0

ajax リクエストがまだ実行されていることをユーザーに示すものを作成する必要があります。

私は角度モジュールを持っています:

var myModule = angular.module('myModule', [
    'ngRoute',
    'ngCookies',
    'localization',
    'myControllers',
    'myServices'
]);

私のサービスは次のようになります。

var myServices = angular.module('myServices', ['ngResource']);
myServices.factory('MyInfo', ['$resource',function($resource){
    return $resource('/api/:method', {}, {
        getSettings: {method:'POST', params:{method:'get_my_settings'}},
        getInfo: {method:'POST',params:{method:'get_my_info'}}
    });
}]);

そして私のコントローラー:

var myControllers = angular.module('myControllers', []);
myControllers.controller('someCtrl', ['$scope', 'MyInfo',
   function($scope, MyInfo) {
      $scope.myInfo = MyInfo.getInfo();
   }
]);

すべてがうまくいきます!しかし、リクエストを送信する前に何らかのアクションを開始し、リクエストが完了して応答が受信されたときにこのアクションを終了するにはどうすればよいですか?

jquery の ajax には、「beforeSend」と「complete」というパラメーターがあり、送信前と要求の完了時に何を行うかを定義できます。

角度でそれを行う方法は?

ありがとう

4

1 に答える 1

0

$httpAngularは、プロパティを持つモジュールへのアクセスを提供しpendingRequestsます。

例を参照してください: https://github.com/angular-app/angular-app/blob/master/client/src/common/services/httpRequestTracker.js

彼らはサービスを作成しています:

angular.module('services.httpRequestTracker', [])

.factory('httpRequestTracker', ['$http',
    function($http) {

        var httpRequestTracker = {};
        httpRequestTracker.hasPendingRequests = function() {
            return $http.pendingRequests.length > 0;
        };

        return httpRequestTracker;
    }
])

次に、このサービスが保留中のリクエストを返したときに ajax ローダー (またはその他のもの) を表示するためのディレクティブを作成できます。

angular.module('directives.ajaxLoader', [
    'services.httpRequestTracker'
])

.directive('ajaxLoader', ['httpRequestTracker',
    function(httpRequestTracker) {
        return {
            templateUrl: 'common/ajaxLoader.tpl.html',
            restrict: 'EA',
            replace: true,
            scope: true,
            link: function($scope) { // This function can have more parameters after $scope, $element, $attrs, $controller
                $scope.hasPendingRequests = function() {
                    return httpRequestTracker.hasPendingRequests();
                };
            }
        };
    }
])

ajaxLoader.tpl.html :

<div class="fade" ng-class="{in: hasPendingRequests(), out: !hasPendingRequests()}">
    LOADING ...
</div>

お役に立てれば

于 2014-04-14T10:25:10.917 に答える