Incorporating promises into native route resolves

AngularJS routing supports resolves, which allow you to demand that some work should be finished before the actual route change process begins. Routing resolves accept one or more functions, which can either return values or promise objects that it will attempt to resolve.

How to do it…

Resolves are declared in the route definition, as follows:

(app.js)

angular.module('myApp', ['ngRoute'])
.config(function($routeProvider){
  $routeProvider
  .when('/myUrl', {
    template: '<h1>Resolved!</h1>',
    // resolved values are injected by property name
    controller: function($log, myPromise, myData) {
      $log.log(myPromise, myData);
    },
    resolve: {
      // $q injected into resolve function
      myPromise: function($q) {
        var deferred ...

Get AngularJS Web Application Development Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.