angular2:路由参数的传递和接收

首先回顾一下如何配置路由:

import {  RouterModule } from '@angular/router';

@NgModule({

  RouterModule.forRooter([{

    path: 'page1',

    component: Page1Component

  }])

})

如果想通过url给下一个页面传递一个名为name的参数,需要这样配置:

import {  RouterModule } from '@angular/router';

@NgModule({

  RouterModule.forRooter([{

    path: 'page2/:name',

    component: Page2Component

  }])

})

那么page2页面如何接受这个name参数呢?首先我们需要导入ActivatedRoute和Params服务,同时需要导入switchMap运算符。

import { ActivatedRoute, Params } from '@angular/router';

import 'rxjs/add/operator/switchMap';

在Page2Component的构造函数中将ActivatedRoute的值保存到私有变量中:

export class Page2Component {

  name: string;

  constructor(private route: ActivatedRoute){}

}

定义一个sayHello的方法接受参数并输出问候语句:

export class Page2Component {

  name: string;

  constructor(private route: ActivatedRoute){}

  sayHello(): void {

     this.route.params

       .switchMap((params: Params)  => this.name = params['name'])

    .subscribe(():void => {console.log('hello,'+ this.name)});

  }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Lesson11、首先确保安装了Node.js和npm依赖包管理工具2、在git上克隆官方示例程序 git clo...
    冰_心阅读 2,743评论 0 16
  • 前言 今天是2017年3月7日,Angular 2.0目前最新版本是 2.0.0-beta.17。网络上搜索到的A...
    程序员长春阅读 3,848评论 1 22
  • 路由:根据不同地址加载不同组件,实现单页面应用 # 1 路由基础知识 ================= 在ang...
    __凌阅读 710评论 0 0
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,099评论 19 139
  • 亲爱的孕妈妈们,大家早上好,我是邯郸瑞思凯诗瑜伽馆的媛媛老师,我们是第一家专业做孕产瑜伽的会馆。 孕妇瑜伽的益处,...
    媛媛教练阅读 239评论 0 0