上一篇:Angular2入门系列教程-服务


  上一篇文章我们将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-路由(一)-使用简单的路由并在在路由中传递参数的更多相关文章

  1. Angular2入门系列教程6-路由(二)-使用多层级路由并在在路由中传递复杂参数

    上一篇:Angular2入门系列教程5-路由(一)-使用简单的路由并在在路由中传递参数 之前介绍了简单的路由以及传参,这篇文章我们将要学习复杂一些的路由以及传递其他附加参数.一个好的路由系统可以使我们 ...

  2. Angular2入门系列教程7-HTTP(一)-使用Angular2自带的http进行网络请求

    上一篇:Angular2入门系列教程6-路由(二)-使用多层级路由并在在路由中传递复杂参数 感觉这篇不是很好写,因为涉及到网络请求,如果采用真实的网络请求,这个例子大家拿到手估计还要自己写一个web ...

  3. Angular2入门系列教程4-服务

    上一篇文章 Angular2入门系列教程-多个组件,主从关系 在编程中,我们通常会将数据提供单独分离出来,以免在编写程序的过程中反复复制粘贴数据请求的代码 Angular2中提供了依赖注入的概念,使得 ...

  4. Angular2入门系列教程1-使用Angular-cli搭建Angular2开发环境

    一直在学Angular2,百忙之中抽点时间来写个简单的教程. 2016年是前端飞速发展的一年,前端越来越形成了(web component)组件化的编程模式:以前Jquery通吃一切的田园时代一去不复 ...

  5. Angular2入门系列教程3-多个组件,主从关系

    上一篇 Angular2项目初体验-编写自己的第一个组件 好了,前面简单介绍了Angular2的基本开发,并且写了一个非常简单的组件,这篇文章我们将要学会编写多个组件并且有主从关系 现在,假设我们要做 ...

  6. Angular2入门系列教程2-项目初体验-编写自己的第一个组件

    上一篇 使用Angular-cli搭建Angular2开发环境 Angular2采用组件的编写模式,或者说,Angular2必须使用组件编写,没有组件,你甚至不能将Angular2项目启动起来 紧接着 ...

  7. Angular2入门系列(五)———— 路由参数设置

    Angular2入门系列(五)---- 路由参数设置路由配置: { path: '', component: CarProFile, children: [ { path: 'add', compon ...

  8. ASP.NET MVC 入门系列教程

    ASP.NET MVC 入门系列教程 博客园ASP.NET MVC 技术专题 http://kb.cnblogs.com/zt/mvc/ 一个居于ASP.NET MVC Beta的系列入门文章,有朋友 ...

  9. Qt快速入门系列教程目录

    Qt快速入门系列教程目录

随机推荐

  1. Java多线程基础学习(一)

    1. 创建线程    1.1 通过构造函数:public Thread(Runnable target, String name){}  或:public Thread(Runnable target ...

  2. Visual Studio Code 代理设置

    Visual Studio Code (简称 VS Code)是由微软研发的一款免费.开源的跨平台文本(代码)编辑器,在十多年的编程经历中,我使用过非常多的的代码编辑器(包括 IDE),例如 Fron ...

  3. JdbcTemplate+PageImpl实现多表分页查询

    一.基础实体 @MappedSuperclass public abstract class AbsIdEntity implements Serializable { private static ...

  4. JavaScript动画-碰撞检测

    ▓▓▓▓▓▓ 大致介绍 碰撞检测是指在页面中有多个元素时,拖拽一个元素会出现碰撞问题,碰撞检测是以模拟拖拽和磁性吸附中的范围限定为基础的 效果:碰撞检测 ▓▓▓▓▓▓ 碰撞检测 先来看看碰撞检测的原理 ...

  5. nodejs模块发布及命令行程序开发

    前置技能 npm工具为nodejs提供了一个模块和管理程序模块依赖的机制,当我们希望把模块贡献出去给他人使用时,可以把我们的程序发布到npm提供的公共仓库中,为了方便模块的管理,npm规定要使用一个叫 ...

  6. python通过protobuf实现rpc

    由于项目组现在用的rpc是基于google protobuf rpc协议实现的,所以花了点时间了解下protobuf rpc.rpc对于做分布式系统的人来说肯定不陌生,对于rpc不了解的童鞋可以自行g ...

  7. ASP.NET Core project.json imports 是什么意思?

    示例代码: "frameworks": { "netcoreapp1.0.0": { "imports" : "portable- ...

  8. 【NLP】Python NLTK处理原始文本

    Python NLTK 处理原始文本 作者:白宁超 2016年11月8日22:45:44 摘要:NLTK是由宾夕法尼亚大学计算机和信息科学使用python语言实现的一种自然语言工具包,其收集的大量公开 ...

  9. Postman接口调试神器-Chrome浏览器插件

    首先大家可以去这个地址下载 Postman_v4.1.3 这个版本,我用的就是这个版本 http://chromecj.com/web-development/2014-09/60/download. ...

  10. 分享两个BPM配置小技巧

    1.小技巧 流程图修改后发布的话版本号会+1,修改次数多了之后可能会导致版本号很高,这个时候可以将流程导出,然后删除对应的流程包再导入,发布数据模型和流程图之后,版本清零 2.小技巧 有的同事入职后使 ...