trying to add loading wheel using angular when i make ajax call?

后端 未结 4 1008
小鲜肉
小鲜肉 2021-01-26 03:03

I am trying to implement loading wheel directive when we make ajax call so during the response time i want to display loading wheen, With below code i do not see any error neith

4条回答
  •  余生分开走
    2021-01-26 03:51

    Implementing an interceptor for HTTP requests. Inside the interceptor you will fire events that you will be able to listen across the application.

    Once it is happening you can use the events inside your main controller(or some directive) to show hide the loader.

    MyApp.factory('Global-httpInterceptor', ['$q', '$rootScope', '$log', function ($q, $rootScope, $log) {
    
        var numLoadings = 0;
    
        return {
            request: function (config) {
    
                numLoadings++;
                // Show loader
                $rootScope.$broadcast("ajax:start", { $config: config });
                return config || $q.when(config);
    
            },
            response: function (response) {
    
                if ((--numLoadings) === 0) {
                    // Hide loader
                    $rootScope.$broadcast("ajax:finished", { $config: response });
                }
                $rootScope.$broadcast("ajax:success", { $response: response });
    
                return response || $q.when(response);
    
            },
            responseError: function (response) {
    
                if (!(--numLoadings)) {
                    // Hide loader
                    $rootScope.$broadcast("ajax:finished", { $response: response });
                }
                $rootScope.$broadcast("ajax:error", { $response: response });
                return $q.reject(response);
            }
        };
    }])
    .config(['$httpProvider', function ($httpProvider) {
        $httpProvider.interceptors.push('Global-httpInterceptor');
    }]);
    

    Example Use

    angular.module('App', [])
      .directive('loading', function () {
          return {
            restrict: 'E',
            replace:true,
            template: '
    LOADING...
    ', link: function (scope, element, attr) { $rootScope.$on("ajax:start", function () { element.show(); }); $rootScope.$on("ajax:finished", function () { element.hide() }); } } })

    And at the view remains the same

    
    

提交回复
热议问题