路由基本使用

2019-01-17  本文已影响0人  2764906e4d3d

使用Anglar Router导航

  1. 路由基础,路由相关对象
  1. 新建一个路由项目,并生成一个home组件和一个product组件

ng new router –routing
ng g component home
ng g component product

  1. 会额外生成一个app-routing-module.ts模块,在主模块的import会导入一个AppRoutingModule,在路由模块中配置路由
import {HomeComponent} from './home/home.component'
import {ProductComponent} from './product/product.component'
const routes: Routes = [
  {path:'',component:HomeComponent},
  {path:'product',component:ProductComponent}
];
  1. 使用路由进行导航()表示事件绑定,表示绑定click事件(类似vue的@)
<a [routerLink]="['/']">主页</a>
<a [routerLink]="['/product']">商品详情</a>
<input type="button" value="商品详情" (click)="toProductDetails()">
<router-outlet></router-outlet>
  1. 使用绑定的click跳转路由
export class AppComponent {
  title = 'route';
  constructor(private router:Router) {
    
  }
  toProductDetails() {
    this.router.navigate(['/product'])
  }
}
  1. 通过这样的配置,当用户访问不存在的地址时,页面显示code404组件的内容(在设置这个路由时,要把这个通配符的路由放到最后,因为它是最通用的路由,只有当路由匹配不到时,才能够让其匹配)
{path:'**',component:Code404Component},

在路由时传递数据

  1. 在查询参数中传递数据,/product?id=1&name=2通过ActivatedRoute.queryParams[id],获取id的值
<a [routerLink]="['/product']" [queryParams]="{id:1}">商品详情</a>
export class ProductComponent implements OnInit {
  private  productId:number
  constructor( private routeInfo:ActivatedRoute){
    
  }
  ngOnInit(){
    this.productId=this.routeInfo.snapshot.queryParams["id"]  }
}
  1. 在路由的路径中传递数据,{path:/product/:id} => /product/1,ActivatedRoute.params[id]获取id
<a [routerLink]="['/product',1]">商品详情</a>
export class ProductComponent implements OnInit {
  private  productId:number
  constructor( private routeInfo:ActivatedRoute){

  }
  ngOnInit(){
    this.productId=this.routeInfo.snapshot.params["id"]  }
}
this.routeInfo=this.subscribe((params:Params)=>this.productId=params["id"])
  1. 在路由配置中传递数据,{path:'product',component:ProductComponent,data:[{isProd:true}]},ActivatedRoute.data[0][isProd]来获取isProd的值

重定向路由

const routes: Routes = [
  {path:'',redirectTo:'/home',pathMatch:'full'},
  {path:'home',component:HomeComponent},
  {path:'product',component:ProductComponent},
  {path:'**',component:Code404Component},

];
上一篇 下一篇

猜你喜欢

热点阅读