Angular2入门系列教程5-路由(一)-使用简单的路由并在在路由中传递参数

上一篇文章咱们将Angular2的数据服务分离出来,学习了Angular2的依赖注入,这篇文章咱们将要学习Angualr2的路由css

  为了编写样式方便,咱们这篇文章开始引入第三方的css库materializecss,引入方法直接在index.html中普通引用就能够了html

  众所周知,Angular出现的目的就是解决web编程的一些限制,让咱们编写的网页能像App同样运做,咱们如今称之为单页面应用(SPA),单页面应用程序有诸多好处,譬如页面响应快,良好的先后端分离,对服务器压力小等等,固然也有不利于SEO等缺点。git

  而实现SPA最重要的那固然是路由,Angular2提供的路由可让咱们在页面间随意的切换而不用刷新页面,下面开始咱们的路由之旅github

  假设你已经跟上了咱们的进度,那就在src/app目录下创建一个app.routing.ts的文件,代码以下web

  

复制代码

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,这是一个路由的配置数组,咱们须要使用它来配置咱们的路由bootstrap

  接下来咱们将咱们的组件都导入了进来,使用一个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

 

https://blog.csdn.net/xwnxwn/article/details/81840194

相关文章
相关标签/搜索