user605331
user605331

Reputation: 3788

What do do while resolve function is resolving?

I like the ability for Angular's router to 'resolve' data for me before transferring control to a controller. How can I show something to the user (spinner, "loading...", etc.) while waiting for a route's resolve function to complete, in the case of an ajax call getting run for the resolve function?

Here's an example from a router that shows what I mean:

.when('/users/:userId/profile', {
  templateUrl: 'views/profile.html',
  controller: 'ProfileCtrl',
  resolve: {
    userProfile: ['$route', 'ProfileService', function ($route, ProfileService) {
      return ProfileService.loadProfile($route.current.params.userId);
    }]
  }
})

As I understand it, "ProfileCtrl" does not get created until "userProfile" has been resolved. That means I can't put code there to run while waiting for the resolve function to complete. In my case "ProfileService.loadProfile" makes and HTTP request, so for the sake of this example, let's say it takes a few seconds to return.

What's the recommended way to show something to the user while waiting for this?

Upvotes: 0

Views: 85

Answers (1)

user2936314
user2936314

Reputation: 1792

You can use $routeChangeStart and $routeChangeSuccess to set some boolean that is used to display a loading animation or whatever in your view:

angular.module('myApp').run(function($rootScope) {
    $rootScope.$on('$routeChangeStart', function() {
        $rootScope.isLoading = true;
    })
    $rootScope.$on('$routeChangeSuccess', function() {
        $rootScope.isLoading = false;
    })
})

in your template you'd have something like:

<div class='loading' ng-show='isLoading'></div>

Or since that is linked to a template which may or may not be available, put class on the page body:

<body ng-class='loading: isLoading'>

</body>

and style it however you like.

As per https://docs.angularjs.org/api/ngRoute/service/$route 'Once all of the dependencies are resolved $routeChangeSuccess is fired.' There is also routeChangeError if you want to tell users when there is a problem with your ajax/resolve. ui-router has analogous stateChangeStart etc.

Upvotes: 1

Related Questions