angular2/4 路由参数详解

参考官网 《路由到视图》

文章目录

    • 路由配置
      • 不带参数的路由配置
      • 路径带参数的路由配置
      • ?后带参数的路由配置
    • 获取路由参数
    • navigateByUrl和navigate区别
    • 完整例子
      • settings.component.ts
      • ProfileSettingsComponent
      • password.settings.component.ts
      • AppRoutingModule
      • app.component.html

路由配置

不带参数的路由配置

假设我们定义了一个路由

{ path: 'heroes', component: HeroListComponent }
  • routerLink配置路由:
//页面不会刷新
 <a routerLink="/heroes">Heroes</a>

注意:routerLink的作用是页面不会被重新加载,我们也可以配置原始的href形式的,只不过页面此时会重新加载,也就是会产生一次刷新。

//页面会刷新
<a href="/heroes">Heroes</a>
  • 用navigate实现路由跳转:
this.router.navigate(['/heroes']);
  • 用navigateByUrl实现路由跳转:
 this.router.navigateByUrl('/heroes');

路径带参数的路由配置

假设我们定义了一个路由

  { path: 'hero/:id', component: HeroDetailComponent }

:id令牌会为路由参数在路径中创建一个“空位”。在这里,这种配置会让路由器把英雄的 id 插入到那个“空位”中。会匹配类似localhost:4200/hero/15

  • routerLink配置路由:
<a [routerLink]="['/hero', hero.id]">

注意:routerLink的外层包裹了[],这样的html会识别出是个动态指令,会替换变量hero.id,并拼接成完整的链接。

router_link.d.ts 源码 注释


 * For instance `['/team', teamId, 'user', userName, {details: true}]`
 * means that we want to generate a link to `/team/11/user/bob;details=true`.
 *
 * Multiple static segments can be merged into one
 * (e.g., `['/team/11/user', userName, {details: true}]`).
 export declare class RouterLink
  • 用navigate实现路由跳转:
this.router.navigate(['/hero'+hero.id]);
  • 用navigateByUrl实现路由跳转:
 this.router.navigateByUrl('/heroes'+hero.id);

?后带参数的路由配置

假设我们的url形式如http://localhost:4200/settings/profile?name=lisi,?后面有参数name,那么我们如何配置路由呢

  • routerLink配置路由:
 <a routerLink='/settings/profile' [queryParams]="{name:'lisi'}">
                        profile</a>

通过[queryParams]传参

  • router.navigate() 实现路由跳转:
    添加一个 NavigationExtras 对象
    let name = 'lisi'
    let navigationExtras: NavigationExtras = {
      queryParams: { 'name':  name}
    };

    // Navigate to the login page with extras
    this.router.navigate(['/settings/profile'], navigationExtras);

我们可以简化配置:
不必设置中间变量,直接赋值一个NavigationExtras对象结构的json

this.router.navigate(['/settings/profile'],  { queryParams: { 'name': 'lisi' } });
  • 用navigateByUrl实现路由跳转:
 this.router.navigateByUrl('/settings/password?name=zhangsan');

获取路由参数


constructor(
  private route: ActivatedRoute     //引入ActivatedRoute     
) {}
ngOnInit() {
  this.route.queryParams.subscribe(params => {
    this.name = params['name'];
    //如果某个操作依赖name的值,需要在此处处理,不能放到括号外面,避免name的值尚未加载
   doSomethingWithName();
  });
}

注意:this.route.queryParams 返回值类型是Observable,需要用subscribe进一步处理,并且获取参数是异步的,因此,后续操作建议在获取参数后再进行。

如果想采用同步的方法获取参数,也是可行的,只要获取snapshot属性

 let snapshot: ActivatedRouteSnapshot = this.activatedRoute.snapshot;
 this.name = snapshot.queryParams['name '];

snapshot包含与当前组件相关的路由的当前瞬间信息。ActivatedRoute也可用于遍历路由器的状态树。 ActivatedRouteSnapshot 也能用于遍历路由器状态树。

navigateByUrl和navigate区别

待续。。。

完整例子

settings.component.ts

作为父组件,加载子组件ProfileSettingsComponentPasswordSettingsComponent
页面上有2个链接和2个按钮,链接测试routerLink,按钮测试navigateByUrl()navigate()

浏览器中输入http://localhost:4200/settings效果图如下:
angular2/4 路由参数详解_第1张图片

import { Router } from '@angular/router';
import { Component } from '@angular/core';

@Component({
    selector: 'settings-page',
    template: `

    
This is settings Page:
`
}) export class SettingsComponent { constructor(private router: Router) { } gotoPassword() { console.log('gotoPassword') this.router.navigateByUrl('/settings/password?name=zhangsan'); //this.router.navigate(['/settings/password'], { queryParams: { 'name': 'zhangsan' } }); } gotoProfile() { console.log('gotoProfile') this.router.navigateByUrl('/settings/profile?name=lisi'); // this.router.navigate(['/settings/profile'], { queryParams: { 'name': 'lisi' } }); } }

ProfileSettingsComponent

子组件,从路由中获取name参数,并显示至页面上。

触发profile链接效果如下:
此时url显示http://localhost:4200/settings/profile?name=lisi
angular2/4 路由参数详解_第2张图片

import { ActivatedRoute } from '@angular/router';
import { Component } from '@angular/core';

@Component({
  selector: 'settings-profile',
  template: `
    
This is ProfileSettingsComponent Page: name is {{name}}
`
}) export class ProfileSettingsComponent { name; constructor(private activatedRoute: ActivatedRoute) { } ngOnInit() { this.activatedRoute.queryParams.subscribe( params => { this.name = params['name']; } ); } }

password.settings.component.ts

子组件,从路由中获取name参数,并显示至页面上

触发password链接效果如下:
此时url显示http://localhost:4200/settings/password?name=zhangsan
angular2/4 路由参数详解_第3张图片

import { ActivatedRoute } from '@angular/router';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'settings-password',
  template: `
    
This is PasswordSettingsComponent Page: name is {{name}}
`
}) export class PasswordSettingsComponent implements OnInit { name; constructor(private activatedRoute: ActivatedRoute) { } ngOnInit() { this.activatedRoute.queryParams.subscribe( params => { this.name = params['name']; } ); } }

AppRoutingModule

路由配置

import { PasswordSettingsComponent } from './password.settings.component';
import { ProfileSettingsComponent } from './profile.settings.component ';
import { SettingsComponent } from './settings.component';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { FormsModule } from '@angular/forms';

export const ROUTES: Routes = [
  {
    path: 'settings',
    component: SettingsComponent,
    children: [
      { path: 'profile', component: ProfileSettingsComponent },
      { path: 'password', component: PasswordSettingsComponent }
    ]
  }
];

@NgModule({
  declarations: [],
  imports: [RouterModule.forRoot(ROUTES), FormsModule],
  exports: [RouterModule]
})
export class AppRoutingModule { }

app.component.html

            <!--第一级路由-->
          <router-outlet></router-outlet>

你可能感兴趣的:(angular2/4 路由参数详解)