Prevent flicker when Angular route change until model gets loaded (Mini-Challenge 10) Answer

Check out Mini-challenge 10 Instructions

Answer:route

The $routeProvider service’s resolve property allows delaying of route change until data is loaded.

First define a route with resolve attribute like this.

angular.module('myApp', ['myAppFilters', 'myAppServices', 'myAppDirectives']).
  config(['$routeProvider', function($routeProvider) {
    $routeProvider.
      when('/users', {
        templateUrl: 'partials/user-list.html', 
        controller: userListCtrl, 
        resolve: userListCtrl.resolve}).
      when('/users/:userId', {
        templateUrl: 'partials/user-detail.html', 
        controller: userDetailCtrl, 
        resolve: userDetailCtrl.resolve}).
      otherwise({redirectTo: '/users'});
}]);

Notice that the resolve property is defined on the route.

function userListCtrl($scope, users) {
  $scope.users = users;
}

userListCtrl.resolve = {
  users: function(user, $q) {
    var deferred = $q.defer();
    user.query(function(successData) {
            deferred.resolve(successData); 
    }, function(errorData) {
            deferred.reject(); 
    });
    return deferred.promise;
  },
  delay: function($q, $defer) {
    var delay = $q.defer();
    $defer(delay.resolve, 1000);
    return delay.promise;
  }
}

 

Notice that the controller definition contains a resolve object which declares users prop which should be available to the controller constructor and gets injected as dependency and it is defined in the resolve property.

The resolve.users function is responsible for returning a promise. All of the promises are collected and the route change is delayed until after all of the promises are resolved, in this example we are delaying the promise to better illustrate the example.

 

References:

https://docs.angularjs.org/api/ngRoute/provider/$routeProvider

If you have a solution for this challenge, different from the proposal solution on this post, don’t be shy and share it with us 🙂