‘Resolve’ comes to our rescue when we want to fetch some data or check some condition before loading the view.

Resolve is a list of tasks that should be done before the controller instantiates or the view is loaded. What it means is we are telling angular, “before you route to this view perform all these tasks mentioned in the ‘resolve’ “. These ‘tasks’ that we mention are ‘promises’.

In this example we will make an API call before the view loads. We will use the ‘The Star Wars API (SWAPI)’ for this example too.

This is the fifth post in a series of posts about fetching data in angularjs. Here are the topics covered in this series.

We have added three files to the ‘resolve’ folder.

resolve folder structure

Resolve – folder structure

As always, let’s start by updating the ‘index.html’ file :


        Fetching Data In Angularjs
  1. Data In Controller
  2. Fetch data stored in a service
  3. Data In A JSON File
  4. API call to get data
  5. Resolve

Changes that we have made :

  • First we add a link to the fifth ‘li’ – ‘Resolve'(‘/resolve’ is the fifth route we will define).
  • Finally we add two more scripts files – ‘resolveController.js’, ‘resolveService.js’.

Next we update the ‘appModule.js’ file.


var fetchDataApp = angular.module( 'fetchDataApp', [
] );
fetchDataApp.config( [ '$routeProvider', function( $routeProvider ) {
    when( '/dataincontroller', {
      templateUrl: 'modules/dataInController/dataInController.html',
      controller: 'dicCntrl'
    } )
    .when( '/datainservice', {
      templateUrl: 'modules/dataInService/dataInService.html',
      controller: 'disCntrl'
    } )
    .when( '/datainjson', {
      templateUrl: 'modules/dataInJsonFile/dataInJson.html',
      controller: 'dijCntrl'
    } )
    .when( '/apicall', {
       templateUrl: 'modules/apiCall/apiCall.html',
       controller: 'acCntrl'
     } )
    .when( '/resolve', {
      templateUrl: 'modules/resolve/resolve.html',
      controller: 'rCntrl'
    } );
} ] );

Here is what is going on :

  • First we tell angular that there is one more module called ‘resolveCntrl’.
  • Next we define our fifth route ‘/resolve’.
  • Lastly we tell angular what html file to use for the view and the controller to be used for this route.

Let’s add resolve to our route.

.when( '/resolve', {
  templateUrl: 'modules/resolve/resolve.html',
    controller: 'rCntrl',
    resolve: {
      starshipData: ['rService', function( rService ) {
        return rService.then( function( response ) {
          return response;
        }, function( response ) {
          return response;
        } )
      } ]
 } );

A resolve contains one or more promises that must resolve successfully before the route will change. In our example, we have just one ‘starshipData’. We have to inject this promise in our controller. Then the controller will wait till this promise is resolved or rejected before it’s initialisation.

Now, since our API call code is in the service, we are injecting the service ‘rService’ and use it to return the response. Over to have a look at the service.


fetchDataApp.service( 'rService', function( $http, $q ) {
  var deferred = $q.defer();
  $http.get( 'http://swapi.co/api/starships/9/' ).then( function( response ) {
	  deferred.resolve( response );
  }, function( response ) {
	  deferred.reject( response.statusText );
  } );
  return deferred.promise;
} );

Our service is similar to the one in ‘apiCall’ module. This service returns a promise, if the API call is a success we return the response. And if the API call fails we return the ‘statusText’ (The SWAPI returns the error message in the ‘statusText’ key of the response).

Now let’s have a look at our controller


var resolveCntrl = angular.module( 'resolveCntrl', [] );
resolveCntrl.controller( 'rCntrl', [ '$scope', 'starshipData', function( $scope, starshipData ) {
  $scope.apiSuccess = true;
  $scope.charJson = starshipData;
  if( typeof starshipData === 'string' ) {
    $scope.apiSuccess = false;
} ] );

In our controller we are injecting the ‘starshipData’ promise. So that the contoller initialisation is waiting till it gets a response from the ‘starshipData’ promise. Now, in our service we are returning the error string if the API call fails. Hence we are checking the ‘typeof’ response. If it is a string that means there is an error and we can handle it accordingly. That’s it in the controller. Let’s have a look at the HTML. ‘apiSuccess’ is used to show the correct ‘div’ in our view.



API end point: http://swapi.co/api/starships/9/

Details of starship 9

  • Name : {{charJson.data.name}}
  • Model : {{charJson.data.model}}
  • Starship Class : {{charJson.data.starship_class}}
  • Cargo Capacity : {{charJson.data.cargo_capacity}}
  • Length : {{charJson.data.length}}
Error : {{charJson}}

We have two divs, one to show data if the API call is a success and the other to show error message in case the API call fails. We are doing this using the ‘ng-if’ directive. The ‘ng-if’ directive makes the decision based on the value of ‘apiSuccess’.

If you look carefully, we have an additional key ‘data’ that is wrapped around our response. This is because we have used resolve.

That is all for resolve.

You can find the code on Github