angular 路由配置

2019-08-05  本文已影响0人  不染事非

1.路由配置

const routes: Routes = [
    {path: '', component: HomeComponent}
];

在做路由配置时path属性不要用’/'开头,因为angular本身会根据path的值做相应的解析生成url。

<input type="button" value="我是详情" (click)="toStockDetail()">

方法在app.component.ts中声明:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  constructor(private router: Router){
        
  }
  toStockDetail(){
    this.router.navigate(['/stock']);
  }
}

通配符写在整个路由配置的最后面。

2.数据传递

1.在查询参数中传递数据
2.在路由路径中传递数据
3.在路由配置中传递数据
4.在url中传递参数

3.参数快照与参数订阅

this.id = this.routerInfo.snapshot.params["id"]
this.routerInfo.params.subscribe((params:Params)=>this.id = params["id"])

4.重定向路由

{path: '', redirectTo: '/home',pathMatch:'full'}

pathMatch:'full'表示只有访问路径是精准的空字符串时才跳转到/home上。

{path: 'xx', redirectTo: '/home',pathMatch:'prefix'}

pathMatch:'prefix'表示路径是以“xx”开头就可跳转到/home上。

5.子路由

在原有路由的基础上加children属性。将router-outlet声明在哪个子路由就会显示在哪儿。由于声明的是子路由,在访问子路由时是不能以“/”开头的,“/”开头代表在主路由中找,子路由以“./”开头。

{path: 'stock', component: StockComponent,
    children:[
      {path: '', component:BuyerListComponent},
      {path: 'seller/:id', component:SellerListComponent}
    ] 
 }

6.辅助路由

在每个页面都有的一些侧边导航,会用到辅助路由。

{path: 'consult', component: ConsultComponent,outlet:"aux"}
<a [routerLink]="[{outlets: {aux: 'consult'}}]">开始</a><br>

说明:主路由的内容也可以控制,主路由没有设置名字,它有一个默认的关键字——primary,在aux前面加上primary:'home',然后点击,主路由跳转到home。

上一篇 下一篇

猜你喜欢

热点阅读