Rodrigue
Rodrigue

Reputation: 169

put a spinner while $http.get fetches data from RESTful API in angularjs

I am fetching a data with this function in my controller:

var fetchStoreItems = function () {
    return $http.get('/enterprises/_store').then(function (response) {
        $scope.items = response.data;
    }, function (errResponse) {
        console.error("Error while fetching data")
    })
};

It is working fine and fast enough. But what if there are lots of items to fetch?! I want to put a spinner while data is being fetched.

How can I do this?

Upvotes: 1

Views: 1692

Answers (2)

Kop4lyf
Kop4lyf

Reputation: 4590

If you want to use it for some of the rest API calls, kalhano's answer works well. However if you want spinner for all your angular http calls, you might consider using an interceptor.

Please check this link for that: Http call docs with interceptors explained

Upvotes: 1

Kalhan.Toress
Kalhan.Toress

Reputation: 21901

In your controller,

var fetchStoreItems = function () {
    $scope.loading = true;            //define a `$scope` variable; show loading image when ajax starts
    return $http.get('/enterprises/_store').then(function (response) {
        $scope.items = response.data;
        $scope.loading = false;       //hide loading image  when ajax successfully completes
    }, function (errResponse) {
        console.error("Error while fetching data");
        $scope.loading = false;      //hide loading image  when ajax error
    })
};

<img src="pathToLoadingImage" ng-show="loading" />  // show the loading image according to `$scope.loading`

Upvotes: 3

Related Questions