如何在数据加载时在AngularJS中显示等待消息?

时间:2022-08-24 17:07:16

I'm new in AngularJS and trying to find the way how to display wait message while data loading? I mean data starts loading, display message and remove it when data loading is done.

我是AngularJS的新手,在数据加载时如何显示等待消息?我的意思是数据开始加载、显示消息并在数据加载完成时删除它。

I've searched the internet but haven't found anything I need...

我在网上找过了,但是没有找到我需要的东西。

5 个解决方案

#1


44  

<div ng-if="data.dataLoading">
    Loading...
</div>

JS

JS

$scope.data.dataLoading = true;

return someService.getData().then(function (results) {                    
    ...
}).finally(function () {
    $scope.data.dataLoading = false;
});

#2


5  

Depends from where you're loading the data. One solution I used was to create a LoadingService

这取决于数据的加载位置。我使用的一个解决方案是创建LoadingService

app.factory('LoadingService', function($rootScope) {
    return {
        loading : function(message) {
             $rootScope.loadingMessage = message;
        },
        loaded : function() {
             $rootScope.loadingMessage = null;
        }
    }
}).controller('FooController', function($scope,$http,LoadingService) {

   $scope.loadSomeData = function() {
       LoadingService.loading('Data is loading');

       $http.get('/data').finally(function() {
            LoadingService.loaded();
       });
   };
});

Since I had only one place where the message was being displayed I could use RootScope to handle this. If you want to have a loading message multiple times you could write a directive also to handle this like Codezilla posted

因为只有一个地方显示消息,所以我可以使用RootScope来处理。如果您想要多次加载消息,您可以编写一个指令来处理这个问题,比如Codezilla post

#3


1  

Edit: does not work on version 1.3.0 . Use request/response interceptors.

编辑:不支持1.3.0版本。使用请求/响应拦截器。

If you want to listen to all requests globally and display a loading widget whenever there's a request pending, you can count the requests using request/response transformers. You simply add a counter and increase on a new request and decrease it on response. I use a provider for that:

如果您希望全局监听所有请求,并在请求等待时显示装载小部件,您可以使用请求/响应转换器计算请求。您只需添加一个计数器,并增加一个新请求,并在响应时减少它。我使用一个提供者:

$httpProvider
  .defaults
  .transformRequest
  .push(function(data) {
      requestNotificationProvider
      .fireRequestStarted(data);
      return data;
});

And the same for transformResponse. Then the same provider holds the information on how many requests are pending and you can use them in a directive. You can read (& copy/paste the code) a full blog post on that here: http://www.kvetis.com/2014/01/angularjs-loading-widget.html There's a working demo in attached.

转换响应也是如此。然后,相同的提供者保存关于有多少请求被挂起的信息,您可以在指令中使用它们。您可以在这里阅读(&复制/粘贴代码)一篇完整的博客文章:http://www.kvetis.com/2014/01/angularjs- loadingwidget.html

#4


0  

I dont know if is the correct way, but I put on my template

我不知道这样做是否正确,但我把模板贴上去了

 <img id="spinner" ng-src="images/spinner.gif" ng-if="!data" >
 <div ng-repeat="repo in repos | orderBy: repoSortOrder">...</div>

#5


0  

I've answered this question in this * article, but here's a recap of what I did.

我在这篇*文章中已经回答了这个问题,但是下面是我所做的事情的概述。

If you style your code correctly, and make sure all calls to a web service pass through one particular factory function, then you can make that factory function handle showing and hiding your "Please Wait" popup.

如果您正确地样式化代码,并确保对web服务的所有调用都通过一个特定的工厂函数传递,那么您可以使工厂函数句柄显示并隐藏您的“请等待”弹出。

Here's the factory function which I use to call all of my GET web services:

这里是工厂函数,我用它来调用我所有的GET web服务:

myApp.factory('httpGetFactory', function ($http, $q) {
    return function (scope, URL) {
        //  This Factory method calls a GET web service, and displays a modal error message if something goes wrong.
        scope.$broadcast('app-start-loading');          //  Show the "Please wait" popup

        return $http({
            url: URL,
            method: "GET",
            headers: { 'Content-Type': undefined }
        }).then(function (response) {
            scope.$broadcast('app-finish-loading');     //  Hide the "Please wait" popup
            if (typeof response.data === 'object') {
                return response.data;
            } else {
                // invalid response
                return $q.reject(response.data);
            }
        }, function (errorResponse) {
            scope.$broadcast('app-finish-loading');     //  Hide the "Please wait" popup

            //  The WCF Web Service returned an error.  
            //  Let's display the HTTP Status Code, and any statusText which it returned.
            var HTTPErrorNumber = (errorResponse.status == 500) ? "" : "HTTP status code: " + errorResponse.status + "\r\n";
            var HTTPErrorStatusText = errorResponse.statusText;

            var message = HTTPErrorNumber + HTTPErrorStatusText;

            BootstrapDialog.show({
                title: 'Error',
                message: message,
                buttons: [{
                    label: 'OK',
                    action: function (dialog) {
                        dialog.close();
                    },
                    draggable: true
                }]
            });

            return $q.reject(errorResponse.data);
        });
    };
});

This would get called like this:

这就叫做:

myApp.webServicesURL = "http://localhost:15021/Service1.svc";

var dsLoadAllEmployees = function (scope)
{
     //  Load all survey records, from our web server
     $scope.LoadingMessage = "Loading Employees data...";

     var URL = myApp.webServicesURL + "/loadAllEmployees";
     return httpGetFactory(scope, URL);
}

Here's the "Please wait" control which I use on each page..

这是我在每页上使用的“请等待”控件。

<please-wait message="{{LoadingMessage}}" ></please-wait>

... and its code looks like this...

…它的代码是这样的…

myApp.directive('pleaseWait',  
    function ($parse) {
        return {
            restrict: 'E',
            replace: true,
            scope: {
                message: '@message'
            },
            link: function (scope, element, attrs) {
                scope.$on('app-start-loading', function () {
                    element.fadeIn(); 
                });
                scope.$on('app-finish-loading', function(){
                    element.animate({
                        top: "+=15px",
                        opacity: "0"
                    }, 500);
                });
            },
            template: '<div class="cssPleaseWait"><span>{{ message }}</span></div>'
        }
    });

Using this structure, any of my Angular controllers can load data from a web service in just a few lines, and leave the factory to look after showing/hiding the "Please wait" message and to display any errors which occur:

使用这种结构,我的任何一个角控制器都可以在几行内从web服务加载数据,并在显示/隐藏“请等待”消息后离开工厂,并显示发生的任何错误:

   $scope.LoadAllSurveys = function () {
        DataService.dsLoadAllSurveys($scope).then(function (response) {
            //  Success
            $scope.listOfSurveys = response.GetAllSurveysResult;
        });
   }

Nice, hey ?

不错,嘿?

#1


44  

<div ng-if="data.dataLoading">
    Loading...
</div>

JS

JS

$scope.data.dataLoading = true;

return someService.getData().then(function (results) {                    
    ...
}).finally(function () {
    $scope.data.dataLoading = false;
});

#2


5  

Depends from where you're loading the data. One solution I used was to create a LoadingService

这取决于数据的加载位置。我使用的一个解决方案是创建LoadingService

app.factory('LoadingService', function($rootScope) {
    return {
        loading : function(message) {
             $rootScope.loadingMessage = message;
        },
        loaded : function() {
             $rootScope.loadingMessage = null;
        }
    }
}).controller('FooController', function($scope,$http,LoadingService) {

   $scope.loadSomeData = function() {
       LoadingService.loading('Data is loading');

       $http.get('/data').finally(function() {
            LoadingService.loaded();
       });
   };
});

Since I had only one place where the message was being displayed I could use RootScope to handle this. If you want to have a loading message multiple times you could write a directive also to handle this like Codezilla posted

因为只有一个地方显示消息,所以我可以使用RootScope来处理。如果您想要多次加载消息,您可以编写一个指令来处理这个问题,比如Codezilla post

#3


1  

Edit: does not work on version 1.3.0 . Use request/response interceptors.

编辑:不支持1.3.0版本。使用请求/响应拦截器。

If you want to listen to all requests globally and display a loading widget whenever there's a request pending, you can count the requests using request/response transformers. You simply add a counter and increase on a new request and decrease it on response. I use a provider for that:

如果您希望全局监听所有请求,并在请求等待时显示装载小部件,您可以使用请求/响应转换器计算请求。您只需添加一个计数器,并增加一个新请求,并在响应时减少它。我使用一个提供者:

$httpProvider
  .defaults
  .transformRequest
  .push(function(data) {
      requestNotificationProvider
      .fireRequestStarted(data);
      return data;
});

And the same for transformResponse. Then the same provider holds the information on how many requests are pending and you can use them in a directive. You can read (& copy/paste the code) a full blog post on that here: http://www.kvetis.com/2014/01/angularjs-loading-widget.html There's a working demo in attached.

转换响应也是如此。然后,相同的提供者保存关于有多少请求被挂起的信息,您可以在指令中使用它们。您可以在这里阅读(&复制/粘贴代码)一篇完整的博客文章:http://www.kvetis.com/2014/01/angularjs- loadingwidget.html

#4


0  

I dont know if is the correct way, but I put on my template

我不知道这样做是否正确,但我把模板贴上去了

 <img id="spinner" ng-src="images/spinner.gif" ng-if="!data" >
 <div ng-repeat="repo in repos | orderBy: repoSortOrder">...</div>

#5


0  

I've answered this question in this * article, but here's a recap of what I did.

我在这篇*文章中已经回答了这个问题,但是下面是我所做的事情的概述。

If you style your code correctly, and make sure all calls to a web service pass through one particular factory function, then you can make that factory function handle showing and hiding your "Please Wait" popup.

如果您正确地样式化代码,并确保对web服务的所有调用都通过一个特定的工厂函数传递,那么您可以使工厂函数句柄显示并隐藏您的“请等待”弹出。

Here's the factory function which I use to call all of my GET web services:

这里是工厂函数,我用它来调用我所有的GET web服务:

myApp.factory('httpGetFactory', function ($http, $q) {
    return function (scope, URL) {
        //  This Factory method calls a GET web service, and displays a modal error message if something goes wrong.
        scope.$broadcast('app-start-loading');          //  Show the "Please wait" popup

        return $http({
            url: URL,
            method: "GET",
            headers: { 'Content-Type': undefined }
        }).then(function (response) {
            scope.$broadcast('app-finish-loading');     //  Hide the "Please wait" popup
            if (typeof response.data === 'object') {
                return response.data;
            } else {
                // invalid response
                return $q.reject(response.data);
            }
        }, function (errorResponse) {
            scope.$broadcast('app-finish-loading');     //  Hide the "Please wait" popup

            //  The WCF Web Service returned an error.  
            //  Let's display the HTTP Status Code, and any statusText which it returned.
            var HTTPErrorNumber = (errorResponse.status == 500) ? "" : "HTTP status code: " + errorResponse.status + "\r\n";
            var HTTPErrorStatusText = errorResponse.statusText;

            var message = HTTPErrorNumber + HTTPErrorStatusText;

            BootstrapDialog.show({
                title: 'Error',
                message: message,
                buttons: [{
                    label: 'OK',
                    action: function (dialog) {
                        dialog.close();
                    },
                    draggable: true
                }]
            });

            return $q.reject(errorResponse.data);
        });
    };
});

This would get called like this:

这就叫做:

myApp.webServicesURL = "http://localhost:15021/Service1.svc";

var dsLoadAllEmployees = function (scope)
{
     //  Load all survey records, from our web server
     $scope.LoadingMessage = "Loading Employees data...";

     var URL = myApp.webServicesURL + "/loadAllEmployees";
     return httpGetFactory(scope, URL);
}

Here's the "Please wait" control which I use on each page..

这是我在每页上使用的“请等待”控件。

<please-wait message="{{LoadingMessage}}" ></please-wait>

... and its code looks like this...

…它的代码是这样的…

myApp.directive('pleaseWait',  
    function ($parse) {
        return {
            restrict: 'E',
            replace: true,
            scope: {
                message: '@message'
            },
            link: function (scope, element, attrs) {
                scope.$on('app-start-loading', function () {
                    element.fadeIn(); 
                });
                scope.$on('app-finish-loading', function(){
                    element.animate({
                        top: "+=15px",
                        opacity: "0"
                    }, 500);
                });
            },
            template: '<div class="cssPleaseWait"><span>{{ message }}</span></div>'
        }
    });

Using this structure, any of my Angular controllers can load data from a web service in just a few lines, and leave the factory to look after showing/hiding the "Please wait" message and to display any errors which occur:

使用这种结构,我的任何一个角控制器都可以在几行内从web服务加载数据,并在显示/隐藏“请等待”消息后离开工厂,并显示发生的任何错误:

   $scope.LoadAllSurveys = function () {
        DataService.dsLoadAllSurveys($scope).then(function (response) {
            //  Success
            $scope.listOfSurveys = response.GetAllSurveysResult;
        });
   }

Nice, hey ?

不错,嘿?