angular2系列教程(十一)路由嵌套、路由生命周期、matrix URL notation

今天我们要讲的是ng2的路由的第二部分,包括路由嵌套、路由生命周期等知识点。

例子

例子仍然是上节课的例子:

上节课,我们讲解了英雄列表,这节课我们讲解危机中心。

源代码:

https://github.com/lewis617/angular2-tutorial/tree/gh-pages/router

运行方法:

在根目录下运行:

http-server

路由嵌套

我们在app/app.component.ts中定义了路由url和视图组件,其中包括这样一项:

app/app.component.ts

{ // Crisis Center child route
    path: ‘/crisis-center/...‘,
    name: ‘CrisisCenter‘,
    component: CrisisCenterComponent,
    useAsDefault: true
  },

那个...就是代表这个url下面可以定义子路由,也就是嵌套路由。嵌套路由是如何实现的?很简单,只需要在视图组件中再次配置路由即可:

app/crisis-center/crisis-center.component.ts

import {Component}     from ‘angular2/core‘;
import {RouteConfig, RouterOutlet} from ‘angular2/router‘;

import {CrisisListComponent}   from ‘./crisis-list.component‘;
import {CrisisDetailComponent} from ‘./crisis-detail.component‘;
import {CrisisService}         from ‘./crisis.service‘;

@Component({
  template:  `
    <h2>CRISIS CENTER</h2>
    <router-outlet></router-outlet>
  `,
  directives: [RouterOutlet],
  providers:  [CrisisService]
})
@RouteConfig([
  {path:‘/‘,    name: ‘CrisisList‘,   component: CrisisListComponent, useAsDefault: true},
  {path:‘/:id‘, name: ‘CrisisDetail‘, component: CrisisDetailComponent}
])
export class CrisisCenterComponent { }

上述代码,我们干了几件事“:

  1. 写了一个组件,包括h2和router-outlet
  2. 使用@RouteConfig,进行路由配置

这样我们就实现了嵌套路由。就是这么简单。

路由生命周期

路由跳转到别的视图的时候,会触发一个路由的生命周期钩子:routerCanDeactivate:

app/crisis-center/crisis-detail.component.ts

routerCanDeactivate(next: ComponentInstruction, prev: ComponentInstruction) : any {
    // Allow synchronous navigation (`true`) if no crisis or the crisis is unchanged.
    if (!this.crisis || this.crisis.name === this.editName) {
      return true;
    }
    // Otherwise ask the user with the dialog service and return its
    // promise which resolves to true or false when the user decides
    return this._dialog.confirm(‘Discard changes?‘);
  }

这段代码,会在你修改完危机信息后,既不点击save也不点击cancer时候触发。也就是this._dialog.confirm(‘Discard changes?‘);弹出一个对话框:

这里为什么要使用单独的dialog服务呢?为何不直接出发window.confirm()?因为路由的生命周期接受bool或者promise对象(ng1也是这样哦)。而window.confirm并不返回一个promise对象,我们需要对其进行包装:

app/dialog.service.ts

import {Injectable} from ‘angular2/core‘;
/**
 * Async modal dialog service
 * DialogService makes this app easier to test by faking this service.
 * TODO: better modal implemenation that doesn‘t use window.confirm
 */
@Injectable()
export class DialogService {
  /**
   * Ask user to confirm an action. `message` explains the action and choices.
   * Returns promise resolving to `true`=confirm or `false`=cancel
   */
  confirm(message?:string) {
    return new Promise<boolean>((resolve, reject) =>
      resolve(window.confirm(message || ‘Is it OK?‘)));
  };
}

我们使用promise包装了confirm这个方法,使得这个服务,会触发confirm的同时,最后也能返回一个promise。这样以来我们就可以在路由的生命周期中尽情的使用了!

值得一提的是ng1路由的resolve属性也是接受一个promise,有兴趣的同学可以看我在ng1中对wilddog的路由改装:

https://github.com/lewis617/wild-angular-seed/blob/gh-pages/components/wilddog.utils/wilddog.utils.js#L85

matrix URL notation

当我们从危机详情视图返回危机列表视图的时候,我们发现我们url变成了:http://localhost:63342/angular2-tutorial/router/index.html/crisis-center/;id=1;foo=foo

;id=1;foo=foo这个参数是我们没有见过的,我们知道query string一般都是"?"加"&",而这个参数则使用了";",这叫做matrix URL notation。

Matrix URL notation is an idea first floated in a 1996 proposal by the founder of the web, Tim Berners-Lee.

Although matrix notation never made it into the HTML standard, it is legal and it became popular among browser routing systems as a way to isolate parameters belonging to parent and child routes. The Angular Component Router is such a system.

The syntax may seem strange to us but users are unlikely to notice or care as long as the URL can be emailed and pasted into a browser address bar as this one can.

这是ng2官方文档对这个概念的解释,我们从中得知,这个概念用区分参数属于父视图还是子视图。

我们在上节课英雄列表中,发现url是普通的query string。为什么在这里变成了matrix URL notation?因为英雄列表视图没有子视图,没有嵌套路由的概念。而危机中心则使用了嵌套路由,拥有父子视图的嵌套,为了加一区分,ng2的路由系统使用了matrix URL notation这个概念。


教程源代码及目录

如果您觉得本博客教程帮到了您,就赏颗星吧!

https://github.com/lewis617/angular2-tutorial

时间: 2024-07-29 08:04:06

angular2系列教程(十一)路由嵌套、路由生命周期、matrix URL notation的相关文章

angular2系列教程(十)两种启动方法、两个路由服务、引用类型和单例模式的妙用

今天我们要讲的是ng2的路由系统. 例子 例子是官网的例子,包含一个“危机中心”和“英雄列表”,都在一个app中,通过路由来控制切换视图.还包含了promise的用法,服务的用法等多个知识点. 源代码: https://github.com/lewis617/angular2-tutorial/tree/gh-pages/router 运行方法: 在根目录下运行: http-server 引入库文件设置base href 路由并不在ng2中,需要我们额外引入,另外我们需要设置base href,

angular2系列教程(一)hello world

今天我们要讲的是angular2系列教程的第一篇,主要是学习angular2的运行,以及感受conponents以及模板语法. http://lewis617.github.io/angular2-tutorial/hellowold/ 例子 这个例子非常简单,是个双向数据绑定. 运行方法: 全局安装http-server npm install -g http-server 公共部分 公共部分就是你直接复制粘贴拿去用的部分,包括: 1.index.html 2.lib 3.app/main.t

angular2系列教程(六)升级装备、pipe

今天,我们要讲的是angualr2的pipe这个知识点,但是在这之前我们需要升级一下我们的装备,因为之前的装备太“寒酸”了. 例子 这个例子包含两个pipe,一个是stateful,一个是stateless,是直接复制官方的例子.本例子还包含了我对AngularClass/angular2-webpack-starter这个牛逼starter的改写,我会详细讲解配置. 源代码 没有测试 AngularClass/angular2-webpack-starter 这里面包含了Angular 2 (

Spark源码系列(四)图解作业生命周期

这一章我们探索了Spark作业的运行过程,但是没把整个过程描绘出来,好,跟着我走吧,let you know! 我们先回顾一下这个图,Driver Program是我们写的那个程序,它的核心是SparkContext,回想一下,从api的使用角度,RDD都必须通过它来获得. 下面讲一讲它所不为认知的一面,它和其它组件是如何交互的. Driver向Master注册Application过程 SparkContext实例化之后,在内部实例化两个很重要的类,DAGScheduler和TaskSched

iOS系列 基础篇 03 探究应用生命周期

iOS系列 基础篇 03 探究应用生命周期 目录: 1. 非运行状态 - 应用启动场景 2. 点击Home键 - 应用退出场景 3. 挂起重新运行场景 4. 内存清除 - 应用终止场景 5. 结尾 本篇主要探讨的是iOS应用中各种状态的跃迁过程,建议大家通过修改AppDelegate.swift,在每个过程中添加日志输出代码,从而观察其变化. 作为应用程序的委托对象,AppDelegate类在应用程序生命周期的不同阶段会回调不同的方法. 首先,咱们先来了解一下iOS应用的不同状态和他们之间的关系

angular2系列教程(五)Structural directives、再谈组件生命周期

今天,我们要讲的是structural directives和组件生命周期这两个知识点.structural directives顾名思义就是改变dom结构的指令.著名的内建结构指令有 ngIf, ngSwitch and ngFor. 例子 例子是我自己改写的,编写一个structural directives,然后通过这个指令实例化和注销组件,在此同时监视组件生命周期. 源代码 UnlessDirective 这个指令是官网示例中的指令. src/unless.directive.ts im

持久化API(JPA)系列(五)控制实体Bean的生命周期

上篇文章<持久化API(JPA)系列(四)管理器EntityManager--执行数据库更新>中我们讲解了使用实体管理器的各种函数操作数据库的方法. 本文主要讲:控制实体Bean的生命周期. 与会话Bean类似,实体Bean也有自己的生命周期,分别对应不同的状态. 下面我们首先来讲解实体Bean的状态和生命周期事件: 1.实体Bean生命周期的4种状态 2.实体Bean的事件: @PostLoad @PrePersist和@PostPersist @PreUpdate和@PostUpdate

死磕 java线程系列之线程池深入解析——生命周期

摘自:https://www.cnblogs.com/tong-yuan/p/11748887.html (手机横屏看源码更方便) 注:java源码分析部分如无特殊说明均基于 java8 版本. 注:线程池源码部分如无特殊说明均指ThreadPoolExecutor类. 简介 上一章我们一起重温了下线程的生命周期(六种状态还记得不?),但是你知不知道其实线程池也是有生命周期的呢?! 问题 (1)线程池的状态有哪些? (2)各种状态下对于任务队列中的任务有何影响? 先上源码 其实,在我们讲线程池体

[Spring实战系列](10)初探Bean生命周期

1. 生命周期流程图 Bean在Spring容器中从创建到销毁经历了若干个阶段,在每一个阶段都可以针对Spring如何管理Bean进行个性化定制. 正如你所见,在Bean 准备就绪之前,Bean 工厂执行了若干启动步骤. Spring 对Bean 进行实例化. Spring 将值和Bean 的引用注入进Bean 对应的属性中. 如果Bean 实现了BeanNameAware接口,Spring 将Bean的ID传递给setBeanName() 接口方法. 如果Bean 实现了BeanFactory