In AngularJS, the $routeProvider
service is used to configure routes. When navigating between views, sometimes you need to preload data before rendering a specific route. This can be achieved using resolve
, which ensures that data is fetched before the controller is instantiated.
This guide will walk you through:
- What
resolve
is and why it’s used. - Implementing
resolve
in AngularJS routes. - Handling resolved data in controllers.
- Error handling in
resolve
. - Example application with API data fetching.
Step 1: Understanding resolve
in AngularJS
What is resolve
in AngularJS?
The resolve
property in AngularJS routing allows you to fetch required data before the route is activated. This prevents UI flickering due to asynchronous data loading.
Why Use resolve
?
- Ensures data is loaded before rendering the view.
- Avoids blank screens while waiting for data.
- Improves user experience by preventing half-loaded pages.
Step 2: Setting Up AngularJS Routing with resolve
1. Include AngularJS and ngRoute
Ensure you have AngularJS and the ngRoute
module installed.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AngularJS Resolve Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular-route.min.js"></script>
</head>
<body ng-app="myApp">
<div ng-view></div>
<script src="app.js"></script>
</body>
</html>
Step 3: Implementing resolve
in AngularJS Routing
1. Define the AngularJS Module and Config
Create app.js
and configure routing with resolve
.
var app = angular.module("myApp", ["ngRoute"]);
// Configuring Routes
app.config(function ($routeProvider) {
$routeProvider
.when("/home", {
templateUrl: "home.html",
controller: "HomeController",
resolve: {
userData: function (UserService) {
return UserService.getUserData();
}
}
})
.otherwise({
redirectTo: "/home"
});
});
2. Create a Service for Fetching Data
Services handle API calls and return data to resolve
.
app.service("UserService", function ($http, $q) {
this.getUserData = function () {
var deferred = $q.defer();
// Simulating API request
$http.get("https://jsonplaceholder.typicode.com/users/1")
.then(function (response) {
deferred.resolve(response.data);
})
.catch(function (error) {
deferred.reject("Error loading user data");
});
return deferred.promise;
};
});
3. Handle Resolved Data in Controller
Inject userData
into the controller.
app.controller("HomeController", function ($scope, userData) {
$scope.user = userData;
});
4. Create the Home Page View (home.html
)
<h2>Welcome, {{ user.name }}</h2>
<p>Email: {{ user.email }}</p>
<p>Phone: {{ user.phone }}</p>
Step 4: Handling Errors in resolve
If an error occurs (e.g., failed API request), the route should handle it gracefully. Modify the resolve
function inside app.config
:
resolve: {
userData: function (UserService, $location) {
return UserService.getUserData().catch(function () {
alert("Failed to load user data. Redirecting to home.");
$location.path("/home");
});
}
}
Step 5: Testing the Application
- Open the app in a browser (
index.html
). - The
/home
route fetches and displays user data. - If the API call fails, the user is redirected with an error message.