sjqq

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

 

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

发表于 2019-05-07 15:09  山涧清泉  阅读(213)  评论(0编辑  收藏  举报
 

分类:

技术点:

相关文章: