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. 图标下载网站 http://www.easyicon.net/

    图标下载网站 http://www.easyicon.net/

  2. PHP SPL标准库之SplFixedArray使用实例

    SplFixedArray主要是处理数组相关的主要功能,与普通php array不同的是,它是固定长度的,且以数字为键名的数组,优势就是比普通的数组处理更快. 看看我本机的Benchmark测试: i ...

  3. Android面试题整理【转载】

      面试宝典(5)  http://www.apkbus.com/android-115989-1-1.html 面试的几个回答技巧 http://blog.sina.com.cn/s/blog_ad ...

  4. 传大附件在iis7以上的设置

    IIS7下设置上传附件大小的限制,下载附件限制问题   最近项目中涉及到一个上传附件的问题,项目在本地运行时上传无论多大的附件都是没有问题,但是一旦部署到服务器上以后上传的附件超过一定大小就上传不成功 ...

  5. git reset 理解

    http://www.open-open.com/lib/view/open1397013992747.html 一般在工作中用的比较多的是: git reset --hard <commitI ...

  6. java 集合4(迭代器)

    迭代器使用要注意的问题: 1.迭代器在遍历元素的时候注意事项: 在迭代器迭代元素的过程中,不准使用集合对象改变集合中的元素个数, 如果要添加或删除要用迭代器的方法. 2.如果使用类集合对象改变集合中的 ...

  7. jmeter 构建一个数据库测试计划

    添加用户 第一步你想做的每一个JMeter测试计划是添加一个 线程组 元素. 的线程组 告诉JMeter的用户数量你想模拟,用户应该多长时间 发送请求,他们应该发送的请求的数量. 继续添加Thread ...

  8. centos nginx 安装

    1.下载 wget http://nginx.org/download/nginx-1.7.8.tar.gz 2.解压 tar -zxvf nginx-1.7.8.tar.gz 3.切换目录 cd n ...

  9. phantomjs 乱码解决

    system = require('system') //传递一些需要的参数给js文件 address = system.args[1];//获得命令行第二个参数 ,也就是指定要加载的页面地址,接下来 ...

  10. python与unicode

    Unicode是一种在计算机上使用的字符编码,是为了解决传统的字符编码方案的局限而产生的,它为每种语言中的每个字符设定了统一并且唯一的二进制编码,以满足跨语言.跨平台进行文本转换.处理的要求. Uni ...