Angular2入门系列教程5-路由(一)-使用简单的路由并在在路由中传递参数
上一篇文章我们将Angular2的数据服务分离出来,学习了Angular2的依赖注入,这篇文章我们将要学习Angualr2的路由
为了编写样式方便,我们这篇文章开始引入第三方的css库materializecss,引入方法直接在index.html中普通引用就可以了
众所周知,Angular出现的目的就是解决web编程的一些限制,让我们编写的网页能像App一样运作,我们现在称之为单页面应用(SPA),单页面应用程序有诸多好处,譬如页面响应快,良好的前后端分离,对服务器压力小等等,当然也有不利于SEO等缺点。
而实现SPA最重要的那当然是路由,Angular2提供的路由可以让我们在页面间随意的切换而不用刷新页面,下面开始我们的路由之旅
假设你已经跟上了我们的进度,那就在src/app目录下建立一个app.routing.ts的文件,代码如下
import {RouterModule,Routes} from "@angular/router";
import {NgModule} from "@angular/core";
import { AppComponent } from './app.component';
import { ArticleComponent } from './article/article.component';
import { ArticledetailComponent } from './articledetail/articledetail.component';
const routes:Routes=[
{ path: 'home',component: AppComponent},
{ path: 'article',component: ArticleComponent},
{ path: 'articledetail/:id',component: ArticledetailComponent},
{ path: '',redirectTo:"/home",pathMatch: 'full'}
];
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {}
让我们来看看这个app.routing.ts干了什么事情
首先我们需要使用语句 import {RouterModule,Routes} from "@angular/router"; 导入我们的路由模块RouterModule以获取路由的支持,然后导入了Routes,这是一个路由的配置数组,我们需要使用它来配置我们的路由
接下来我们将我们的组件都导入了进来,使用一个Routes类型的变量去配置路由,方式就如上所写,其中我们看到{ path: 'articledetail:id',component: ArticledetailComponent},中的id,这种路由的访问链接就是http://****.com/articledetail/id
最后,我们使用NgModule装饰器去描述导入和导出的情况,这样,我们的路由表就配置好了,只要在app.module.ts中导任意就可以使用了,顺便细心的朋友可能发现了,我们将BlogService也放到这里去,这样,我们在任意地方都可以使用BlogService了。
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppRoutingModule } from './app.routing';
import {BlogService} from './data/blog.service';
import { AppComponent } from './app.component';
import { ArticleComponent } from './article/article.component';
import { ArticledetailComponent } from './articledetail/articledetail.component';
@NgModule({
declarations: [
AppComponent,
ArticleComponent,
ArticledetailComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
AppRoutingModule
],
providers: [BlogService],
bootstrap: [AppComponent]
})
export class AppModule { }
那么具体要怎么使用路由呢?
上面配置显示我们将AppComponent组件作为了路由起点,那我们就在这个组件里面做些事情
App.Component.html
<div class="container">
<a routerLink="/article" class="btn waves-effect waves-light">博客列表</a>
<a routerLink="/articledetail/1" class="btn waves-effect waves-light">最多阅读</a>
</div>
<router-outlet></router-outlet>
我们看到有两个新东西,一个是routerLink,这个就像我们原本的a标签的href,是指定Angular路由的一个东西
第二个就是router-outlet标签,这个是个导航容器,导航过后,新的组件将会在这里展现
修该过后,我们需要修改articleDetailComponent的代码以支持路由传参的id
articldetail.component.ts
import { Component, OnInit,Input } from '@angular/core';
import {ActivatedRoute,Params} from '@angular/router';
import { Location } from '@angular/common';
import {BLOGS,Blog} from '../data/blog';
import {BlogService} from '../data/blog.service'
import 'rxjs/add/operator/switchMap';
@Component({
selector: 'article-detail',
templateUrl: './articledetail.component.html',
styleUrls:['./articledetail.component.css']
})
export class ArticledetailComponent implements OnInit {
@Input() blog:Blog;
constructor(
private bService: BlogService,
private route: ActivatedRoute,
private location: Location
) {}
ngOnInit() {
let id=this.route.params
.switchMap((params: Params) => params['id'])
.subscribe(x=>this.blog=this.bService.getSelectedBlog(+x))
}
back()
{
this.location.back();
}
}
我们添加了ActivatedRoute,Params用以获取路由参数,由于Angular的路由参数是一个Observable对象,我们使用switchMap去处理它,你现在不用去关心这些,因为,在之后的学习中,我们会专门学习Observable
然后我们添加了一个返回方法,点击就可以返回上一级
看html代码
<div class="articledetail" *ngIf="blog">
<h2>文章明细</h2>
<div class="content">
<div class="row">
<span >ID</span>
<span>{{blog.id}}</span>
</div>
<div class="row">
<span >Title</span>
<input type="text" class="myInput" [(ngModel)]="blog.title"/>
</div>
<div class="row">
<button class="btn" (click)="back()">返回列表</button>
</div>
</div>
</div>
这样,我们的明细就可以显示了。
程序到此还不完全,我们当然还要处理下ArticleComponnet组件,改动很少,只用改动一点儿html代码就行了
article.component.html
<div class="article">
<ul class="articleList">
<li *ngFor="let blog of blogList" [routerLink]="['/articledetail',blog.id]" >
<a>
{{blog.id}}:{{blog.title}}
</a>
</li>
</ul>
<div>
</div>
这里使用的[routerLink]=[]的方式,第一个是路由地址,第二个是参数,就是我们的id
处理完了,我们可以来看看效果了

看到这里,你是否觉得有点。。。生硬,那么我们来为路由加一点儿动画
我们只处理下articleDetail组件
import { Component, OnInit,Input ,HostBinding,
trigger, transition, animate,
style, state } from '@angular/core';
import {ActivatedRoute,Params} from '@angular/router';
import { Location } from '@angular/common';
import {BLOGS,Blog} from '../data/blog';
import {BlogService} from '../data/blog.service'
import 'rxjs/add/operator/switchMap';
@Component({
selector: 'article-detail',
templateUrl: './articledetail.component.html',
styleUrls:['./articledetail.component.css'],
animations: [
trigger('routeAnimation', [
state('*',
style({
opacity: 1,
transform: 'translateX(0)'
})
),
transition(':enter', [
style({
opacity: 0,
transform: 'translateY(-100%)'
}),
animate('0.2s ease-in')
]),
transition(':leave', [
animate('.5s ease-out', style({
opacity: 0,
transform: 'translateY(100%)'
}))
])
])
]
})
export class ArticledetailComponent implements OnInit {
@HostBinding('@routeAnimation') get routeAnimation() {
return true;
}
@HostBinding('style.display') get display() {
return 'block';
}
@HostBinding('style.position') get position() {
return 'absolute';
}
@Input() blog:Blog;
constructor(
private bService: BlogService,
private route: ActivatedRoute,
private location: Location
) {}
ngOnInit() {
let id=this.route.params
.switchMap((params: Params) => params['id'])
.subscribe(x=>this.blog=this.bService.getSelectedBlog(+x))
}
back()
{
this.location.back();
}
}
这里不打算讲解Animate,因为,之后我们会专门介绍Angular2的动画
现在这里放一个空的链接:Angular2入门系列教程:Angular2动画
来看看效果吧

文章的介绍就到这里,有疑问可以给我留言
更新ing。。。
项目已经放到了gitbub上,地址 https://github.com/SeeSharply/LearnAngular
本文章的提交 https://github.com/SeeSharply/LearnAngular/tree/bba4d45b63621a7fc8fd556aa1fc49d397a00552
Angular2入门系列教程5-路由(一)-使用简单的路由并在在路由中传递参数的更多相关文章
- Angular2入门系列教程6-路由(二)-使用多层级路由并在在路由中传递复杂参数
上一篇:Angular2入门系列教程5-路由(一)-使用简单的路由并在在路由中传递参数 之前介绍了简单的路由以及传参,这篇文章我们将要学习复杂一些的路由以及传递其他附加参数.一个好的路由系统可以使我们 ...
- Angular2入门系列教程7-HTTP(一)-使用Angular2自带的http进行网络请求
上一篇:Angular2入门系列教程6-路由(二)-使用多层级路由并在在路由中传递复杂参数 感觉这篇不是很好写,因为涉及到网络请求,如果采用真实的网络请求,这个例子大家拿到手估计还要自己写一个web ...
- Angular2入门系列教程4-服务
上一篇文章 Angular2入门系列教程-多个组件,主从关系 在编程中,我们通常会将数据提供单独分离出来,以免在编写程序的过程中反复复制粘贴数据请求的代码 Angular2中提供了依赖注入的概念,使得 ...
- Angular2入门系列教程1-使用Angular-cli搭建Angular2开发环境
一直在学Angular2,百忙之中抽点时间来写个简单的教程. 2016年是前端飞速发展的一年,前端越来越形成了(web component)组件化的编程模式:以前Jquery通吃一切的田园时代一去不复 ...
- Angular2入门系列教程3-多个组件,主从关系
上一篇 Angular2项目初体验-编写自己的第一个组件 好了,前面简单介绍了Angular2的基本开发,并且写了一个非常简单的组件,这篇文章我们将要学会编写多个组件并且有主从关系 现在,假设我们要做 ...
- Angular2入门系列教程2-项目初体验-编写自己的第一个组件
上一篇 使用Angular-cli搭建Angular2开发环境 Angular2采用组件的编写模式,或者说,Angular2必须使用组件编写,没有组件,你甚至不能将Angular2项目启动起来 紧接着 ...
- Angular2入门系列(五)———— 路由参数设置
Angular2入门系列(五)---- 路由参数设置路由配置: { path: '', component: CarProFile, children: [ { path: 'add', compon ...
- ASP.NET MVC 入门系列教程
ASP.NET MVC 入门系列教程 博客园ASP.NET MVC 技术专题 http://kb.cnblogs.com/zt/mvc/ 一个居于ASP.NET MVC Beta的系列入门文章,有朋友 ...
- Qt快速入门系列教程目录
Qt快速入门系列教程目录
随机推荐
- 用scikit-learn学习主成分分析(PCA)
在主成分分析(PCA)原理总结中,我们对主成分分析(以下简称PCA)的原理做了总结,下面我们就总结下如何使用scikit-learn工具来进行PCA降维. 1. scikit-learn PCA类介绍 ...
- iOS二维码生成、识别、扫描等
二维码扫描 前言: 最近的项目中使用到了二维码,二维码这个模块功能也完成:觉得还是有必要总结一下用来做记录.好长时间没有写二维码了都忘记在差不多了,重新拾起来还是挻快的. 二维码使用场景: 生活中有很 ...
- Ubuntu 16.10 开启PHP错误提示
两个步骤: 修改php.ini配置文件中的error_reporting 和 display_errors两地方内容: sudo vim /etc/php/7.0/apache2/php.ini er ...
- 基于Oracle安装Zabbix
软件版本 Oracle Enterprise Linux 7.1 64bit Oracle Enterprise Edition 12.1.0.2 64bit Zabbix 3.2.1 准备工作 上传 ...
- 带你实现开发者头条APP(四)---首页优化(加入design包)
title: 带你实现开发者头条APP(四)---首页优化(加入design包) tags: design,Toolbar,TabLayout,RecyclerView grammar_cjkRuby ...
- 利用poi导出Excel
import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.r ...
- webpack学习总结
前言 在还未接触webpack,就有几个疑问: 1. webpack本质上是什么? 2. 跟异步模块加载有关系吗? 3. 可否生成多个文件,一定是一个? 4. 被引用的文件有其他异步加载模块怎么办? ...
- iOS--->微信支付小结
iOS--->微信支付小结 说起支付,除了支付宝支付之外,微信支付也是我们三方支付中最重要的方式之一,承接上面总结的支付宝,接下来把微信支付也总结了一下 ***那么首先还是由公司去创建并申请使用 ...
- 【代码笔记】iOS-获得当前的月的天数
一,代码. #import "ViewController.h" @interface ViewController () @end @implementation ViewCon ...
- A*算法应用[转]
转自:http://www.cnblogs.com/zhoug2020/p/3468167.html 这是一篇十分精彩/易懂的博客,感谢原博主!本文通过自己的理解在原博文基础上突出一些重点字眼,句子. ...