zeroliu
zeroliu

Reputation: 1040

How to take advantage of AngularJS $routeprovider resolve feature and keeps a good loading user experience

I have read a few articles about the $routeprovider resolve feature. The main idea comes from this repo created by my favorite AngularJS developer Todd Motto. https://github.com/toddmotto/angularjs-styleguide#controllers

// avoid
function MainCtrl (SomeService) {
  var _this = this;
  // unresolved
  _this.something;
  // resolved asynchronously
  SomeService.doSomething().then(function (response) {
    _this.something = response;
  });
}
angular
  .module('app')
  .controller('MainCtrl', MainCtrl);

// recommended
function config ($routeProvider) {
  $routeProvider
  .when('/', {
    templateUrl: 'views/main.html',
    resolve: {
      // resolve here
    }
  });
}
angular
  .module('app')
  .config(config);

I really like the way how route resolves all the controller dependencies first before loading the controller. It keeps the code very clean. However, if the resolve process takes a significant amount of time, the page will stuck there with no visual feedback until everything finishes loading.

Before I switched to use $routeprovider resolve, I used to put everything in the controller then create a async loading view directive. The directive will display a loading progress bar while all the $http requests are downloading data. I am wondering if there is a way to keep the visual feedback and also put all the resolve steps in the route provider.

Thanks!

Upvotes: 0

Views: 874

Answers (1)

Todd Motto
Todd Motto

Reputation: 913

When the resolves are kicking off, you can hook into $routeChangeStart and $routeChangeSuccess events. These events you listen for and can show or hide ajax spinners/loading messages based on the event type.

More here!

Upvotes: 2

Related Questions