详解Angular5路由传值方式及其相关问题

?目前Angular已经升级到了稳定版本Angular5,这次升级更小更快以及更稳定!路由可以说是Angular甚至是单页应用的核心部分了吧!在angularjs中的路由最大的缺点就是无法嵌套路由,在Angular中解决了这个问题!在Angular中路由不仅仅是页面跳转,其中还有一项叫英雄列表跳转英雄详情!在诸多的列表,不可能给每个英雄做一个详情页,于是乎路由参数起到作用了!通过路由传入参数识别那个英雄的详情!

现在对于路由传值进行详解,首先一种方式是官网的导航到详情的单值id传入,另一种是多数据传入!

1.单值传入


['/hero', hero.id]




<ul class="items">
  <li *ngFor="let hero of heroes$ | async"
   [class.selected]="hero.id === selectedId">
   <a [routerLink]="['/hero', hero.id]">
    <span class="badge">{{ hero.id }}</span>{{ hero.name }}
   </a>
  </li>
</ul>


以上是官网示例

下面我们用我自己的示例介绍一下:

首先是列表页,以及跳转方式
<span><a style="CURSOR: pointer" data="27611" class="copybut" id="copybut27611" onclick="doCopy('code27611')"><U>复制代码</U></a></span> 代码如下:<p *ngFor="let item of items" [routerLink]="['/listDetail',item.id]">{{item.name}}</p>

然后是配置路由:(单值传入的方式需要在详情组件路由配置)


{
  path:'listDetail/:id',
  component:ListDetailComponent
},

传入后就是取到参数,在详情组件的ngOnInit生命周期获取参数


ngOnInit() {
  this.route.params
   .subscribe((params: Params) => {
    this.id = params['id'];
    console.log(this.id);
    console.log('传值');
    console.log(params)
   })
}


2.我们在平时的复杂的业务场景我们需要传多个数据,这时候该怎么办呢?这时候我们就用到了queryParams
<span><a style="CURSOR: pointer" data="19325" class="copybut" id="copybut19325" onclick="doCopy('code19325')"><U>复制代码</U></a></span> 代码如下:<p *ngFor="let data of datas" [routerLink]="['/listDetails']" [queryParams]="{id:data.id,state:data.state}">{{data.name}}</p>
这里数据我是直接拿上去的,同样你可以组织好数据,一个参数放上去,简化html结构,现在有个问题,这样多值传入路由参数怎么配置呢?/:id/:id???我这个参数多少也不是固定的咋办?其实这种方式不需要配置路由!你只需要传入和取到数据就可以了!


ngOnInit() {
  this.route.queryParams
   .subscribe((params: Params) => {
    this.id = params['id'];
    this.state = params['state'];
    console.log(params)
    console.log(this.id);
    console.log(this.state);

   })
}



以上就是Angular路由传值两种方式!希望对大家有帮助!也希望大家多多支持脚本之家。

            
            

猜你喜欢

转载自blog.csdn.net/qq_42485486/article/details/80762006