Delaying AngularJS Route Change for Data Fetching
AngularJS offers a solution to prevent flickering during route transitions when models require data fetching. This technique, analogous to Gmail's behavior, allows you to delay displaying a new route until the necessary model data has been retrieved.
Resolve Property of $routeProvider
The key feature for delaying route changes is the resolve property associated with $routeProvider. By defining a route with a resolve attribute, you specify that data needs to be fetched before the route can transition.
Example
Consider the following example:
// Define a route with a resolve property $routeProvider.when('/phones', { templateUrl: 'partials/phone-list.html', controller: PhoneListCtrl, resolve: PhoneListCtrl.resolve });
The resolve attribute refers to an object where you define functions to fetch the data. For instance:
function PhoneListCtrl($scope, phones) { $scope.phones = phones; $scope.orderProp = 'age'; } PhoneListCtrl.resolve = { phones: function(Phone, $q) { // Deferred object for promise handling var deferred = $q.defer(); // Fetch data via Phone service Phone.query(function(successData) { deferred.resolve(successData); }, function(errorData) { deferred.reject(); // Optionally handle errors }); return deferred.promise; } }
Deferred Promises
Promises are used to represent the asynchronous data fetching process. Each resolve function returns a promise, and AngularJS collects all these promises. The route change is delayed until all promises are resolved, ensuring that the data is ready before displaying the new view.
The above is the detailed content of How Can I Prevent Flickering During AngularJS Route Transitions When Fetching Data?. For more information, please follow other related articles on the PHP Chinese website!