angular+ 路由学习(三)路由带参

  • 如果是和我一样的小白,直接学习官文上的路由和导航的;在里程碑3:英雄特征区开始的,其中前几步是让我们把服务的部分代码拿过来;然后更改代码和目录结构,直接看后面总结代码,因为中间省略了很多;按照步骤来是很坑的;大佬请忽略;)
  • 配置路由,这里将hero-detail作为需要传递参数的组件模块;
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HeroListComponent } from './hero-list/hero-list.component';
import { HeroDetailComponent } from './hero-detail/hero-detail.component';

const heroesRoutes: Routes = [
  {path: 'heroes', component: HeroListComponent},
  {path: 'hero/:id', component: HeroDetailComponent} // 路由带参; hero为路径   /:id 为占位参数,即这里是将传来动态参数id;如localhost:4200/hero/1;即访问id为1的数据;
];

@NgModule({
  imports: [RouterModule.forChild(heroesRoutes)],
  exports: [RouterModule]
})
export class HeroesRoutingModule { }
  • 路由跳转,通过视图的标签属性
  •     <!-- 视图带参跳转 -->
        <a [routerLink]="['/hero', hero.id]">
          <span class="badge">{{hero.id}}</span> {{hero.name}}
        </a>
    
        <a routerLink="/hero/{{hero.id}}">
          <span class="badge">{{hero.id}}</span> {{hero.name}}
        </a>
  • 路由跳转,通过ts方法
  •   // 跳转方法
      goDetailById(heroId){
        this.router.navigate(['hero', heroId]); // 路由跳转;
        // this.router.navigate(['hero',{ id: heroId, flag: true}]); // 多个参数
      }

猜你喜欢

转载自www.cnblogs.com/gushiyoyo/p/11254913.html