In a previous post about testing I mentioned that route resolves can make authoring unit tests for a controller easier. Resolves can also help the user experience.

A resolve is a property you can attach to a route in both ngRoute and the more robust UI router. A resolve contains one or more promises that must resolve successfully before the route will change. This means you can wait for data to become available before showing a view, and simplify the initialization of the model inside a controller because the initial data is given to the controller instead of the controller needing to go out and fetch the data.

As an example, let’s use the following simple service which uses $q to simulate the async work required to fetch some data.

app.factory("messageService", function($q){
    return {
        getMessage: function(){
            return $q.when("Hello World!");
        }
    };
});

And now the routing configuration that will use the service in a resolve.

$routeProvider
    .when("/news", {
        templateUrl: "newsView.html",
        controller: "newsController",
        resolve: {
            message: function(messageService){
                return messageService.getMessage();
        }
    }
})

Resolve is a property on the routing configuration, and each property on resolve can be an injectable function (meaning it can ask for service dependencies). The function should return a promise.

When the promise completes successfully, the resolve property (message in this scenario) is available to inject into a controller function. In other words, all a controller needs to do to grab data gathered during resolve is to ask for the data using the same name as the resolve property (message).

app.controller("newsController", function (message) {
    $scope.message = message;
});

You can work with multiple resolve properties. As an example, let’s introduce a 2nd service. Unlike the messageService, this service is a little bit slow.

app.factory("greetingService", function($q, $timeout){
   return {
       getGreeting: function(){
           var deferred = $q.defer();
           $timeout(function(){
               deferred.resolve("Allo!");
           },2000);
           return deferred.promise;
       }
   }
});

Now the resolve in the routing configuration has two promise producing functions.

.when("/news", {
    templateUrl: "newsView.html",
    controller: "newsController",
    resolve: {
        message: function(messageService){
            return messageService.getMessage();
        },
        greeting: function(greetingService){
            return greetingService.getGreeting();
        }
    }
})

And the associated controller can ask for both message and greeting.

app.controller("newsController", function ($scope, message, greeting) {
    $scope.message = message;
    $scope.greeting = greeting;
});

Composing Resolve

Although there are benefits to moving code out of a controller, there are also drawbacks to having code inside the route definitions. For controllers that require a complicated setup I like to use a small service dedicated to providing resolve features for a controller. The service relies heavily on promise composition and might look like the following.

app.factory("newsControllerInitialData", function(messageService, greetingService, $q) {
    return function() {
        var message = messageService.getMessage();
        var greeting = greetingService.getGreeting();
 
        return $q.all([message, greeting]).then(function(results){
            return {
                message: results[0],
                greeting: results[1]
            };
        });
    }
});

Not only is the code inside a service easier to test than the code inside a route definition, but the route definitions are also easier to read.

.when("/news", {
    templateUrl: "newsView.html",
    controller: "newsController",
    resolve: {
        initialData: function(newsControllerInitialData){
            return newsControllerInitialData();
        }
    }
})

And the controller is also easy.

app.controller("newsController", function ($scope, initialData) {
    $scope.message = initialData.message;
    $scope.greeting = initialData.greeting;
});

One of the keys to all of this working is $q.all, which is a beautiful way to compose promises and run requests in parallel.

routeProvider的更多相关文章

  1. AgularJS中Unknown provider: $routeProvider解决方案

    最近在学习AgularJS, 做到http://angularjs.cn/A00a这一步时发现没有办法执行路由功能, 后来翻看控制台日志,发现提示Unknown provider: $routePro ...

  2. routeProvider路由的使用

    先创建一个主程序文件index.html,内容如下: <!DOCTYPE html> <html ng-app="myApp"> <head> ...

  3. angularJS $routeProvider

    O'Reilly书上的伪代码 var someModule = angular.module('someModule',[...module dependencies]); someModule.co ...

  4. AngularJS---Unknown provider: $routeProvider

    AngularJS路由报错: Unknown provider: $routeProvider 根据先知们的指引,在网上爬贴,有翻到官方的解决文章. 原来在AgularJS1.2.0及其之后的版本中, ...

  5. 26.angularJS $routeProvider

    转自:https://www.cnblogs.com/best/tag/Angular/ O'Reilly书上的伪代码 var someModule = angular.module('someMod ...

  6. AngularJS实例实战

    学习了这么多天的AngularJS,今天想从实战的角度和大家分享一个简单的Demo--用户查询系统,以巩固之前所学知识.功能需求需要满足两点 1.查询所有用户信息,并在前端展示 2.根据id查询用户信 ...

  7. Nodejs之MEAN栈开发(七)---- 用Angular创建单页应用(下)

    上一节我们走通了基本的SPA基础结构,这一节会更彻底的将后端的视图.路由.控制器全部移到前端.篇幅比较长,主要分页面改造.使用AngularUI两大部分以及一些优化路由.使用Angular的其他指令的 ...

  8. Nodejs之MEAN栈开发(六)---- 用Angular创建单页应用(上)

    在上一节中我们学会了如何在页面中添加一个组件以及一些基本的Angular知识,而这一节将用Angular来创建一个单页应用(SPA).这意味着,取代我们之前用Express在服务端运行整个网站逻辑的方 ...

  9. AngularJs之八

    ***今天讲一下angularJs的路由功能: 一:angularJs路由. 1.AngularJS 路由允许我们通过不同的 URL 访问不同的内容. 2.通过 AngularJS 可以实现多视图的单 ...

随机推荐

  1. 理解odbc

    1.解决什么样的问题?不同的数据库产品,具有不同的特性,也就是方言.因此应用程序针对不同的数据库产品,编写不同的代码.如果换了一个数据库产品,还需要重新编写数据库交互部分,不具备扩展和移植.odbc对 ...

  2. Activtiy

    Class Overview An activity is a single, focused thing that the user can do. Almost all activities in ...

  3. 测试分页查询出数据并分文件导出[java工程]

    package cn.shiyanjun.test; import java.util.ArrayList; import java.util.List; public class ExcelTest ...

  4. Mysql 组合查询 UNION 与 UNION ALL

  5. 制作Aspose CHM文档的过程记录

    欢迎和大家交流技术相关问题: 邮箱: jiangxinnju@163.com 博客园地址: http://www.cnblogs.com/jiangxinnju GitHub地址: https://g ...

  6. package-info.java文件详解

    欢迎关注我的社交账号: 博客园地址: http://www.cnblogs.com/jiangxinnju/p/4781259.html GitHub地址: https://github.com/ji ...

  7. node.js关于传送数据的二三事

    配置好node环境后 书写代码 目录结构: . 代码: <!DOCTYPE html> <html lang="en"> <head> < ...

  8. 在Windows Azure上搭建SSTP VPN

    在国内,VPN是用来干嘛的大家都懂的.很久之前我尝试用Azure的Virtual Network搞VPN结果惨败了.最近微博上有基友写了篇文章亲测可行,原文在这里.可惜是英文的.所以我的这篇文章仅仅是 ...

  9. php Composer 报ssl证书错误

    CA证书下载地址:http://curl.haxx.se/docs/caextract.html 修改php.ini文件 openssl.cafile= D:/wamp/php/verify/cace ...

  10. tr设置背景图片

    tr是不能设置背景图片的....