:root{--puock-block-not-tran:100%}

Angular 路径参数和查询参数的使用以及使用场景区别

225次阅读
没有评论

共计 2048 个字符,预计需要花费 6 分钟才能阅读完成。

需求是通过路径在页面下传递不同的渠道信息到后端,Angular 在 Url 中传递参数有两种方式,路由参数和查询参数。一时犯了难,想考究一下两种方式在使用中的区别,以及优劣势。

路径参数的使用

路径参数需要再路由文件中声明:{参数名}, 如下代码所示:

const appRoutes: Routes = [
  ...
  { path: 'hero/:id', component: HeroDetailComponent },
  ...
  { path: '**', component: PageNotFoundComponent }
];
@NgModule({
  imports: [
    RouterModule.forRoot(appRoutes)
  ],
  ...
})
export class AppModule { }

使用时可在模版中使用如下代码跳转。

<a [routerLink]="['/hero', 1]">

也可在js代码中使用路由接口进行跳转

_router.navigate(['/hero', 1]);

component 可以使用 ActivatedRoute 的实例获取传递的值

import { ActivatedRoute } from '@angular/router';
export class HeroDetailComponent implements OnInit, OnDestroy {
    constructor(private readonly _activatedRoute: ActivatedRoute) {}
    ngOnInit() {
      // 通过订阅获取
      this._activatedRoute.params.subscribe(params => {
        const id = params['id'];
        console.log('路径参数的订阅Id值为:', id);
      });
      // 通过快照获取
      const idSnapshot = this._activatedRoute.snapshot.params['id'];
      console.log('路径参数的快照Id值为:', idSnapshot);
    }
}

在获取时采用快照的形式还是订阅的形式取决于这个component是否打算复用,更具体的如果你在HeroDetailComponent 中跳转了 hero/:id 这个路径就需要使用订阅的形式监听路径参数的变化从新绘制界面,因为component不会重新加载ngOnInit不会再次执行。只有从一个另外一个component跳转才会有加载过程。

查询参数的使用

查询参数不需要在路由文件中进行声明, 路由中只要存在hero 这个路径,即可向这个路径传递任何数量以及名称的查询参数,当然不能超过浏览器url限制长度,如下路由声明。

const appRoutes: Routes = [
  ...
  { path: 'hero', component: HeroDetailComponent },
  ...
  { path: '**', component: PageNotFoundComponent }
];
@NgModule({
  imports: [
    RouterModule.forRoot(appRoutes)
  ],
  ...
})
export class AppModule { }

使用时可在模版中使用如下代码跳转。

<a [routerLink]="['/hero']" [queryParams]="{id: 1}">

也可在js代码中使用路由接口进行跳转

_router.navigate(['/hero'], {queryParams: {id: 1}});

component 也是使用 ActivatedRoute 的实例获取传递的值

import { ActivatedRoute } from '@angular/router';
export class HeroDetailComponent implements OnInit, OnDestroy {
    constructor(private readonly _activatedRoute: ActivatedRoute) {}
    ngOnInit() {
      // 通过订阅获取
      this._activatedRoute.queryParams.subscribe(params => {
        const id = params['id'];
        console.log('路径参数的订阅Id值为:', id);
      });
      // 通过快照获取
      const idSnapshot = this._activatedRoute.snapshot.queryParams['id'];
      console.log('路径参数的快照Id值为:', idSnapshot);
    }
}

使用以及加载过程和路径参数完全相同,需要注意的地方也是。

总结使用场景

在 Angular2 以上版本中可选路径参数被去除了,也就是之前 hero/:id? 被去除了,网上有许多如添加一个 hero 路径导航到相同的 component 模块的方式配置可选路径参数,这种是在一般情况下都是不推荐的,这也是路径参数从一般使用上和查询参数的区别,路径参数尽量是必须的,查询参数是可选的。

正文完
 1
太阳
版权声明:本站原创文章,由 太阳 于2021-02-08发表,共计2048字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)