路由配置文件
const routes: Routes = [
{
path:'',
redirectTo:'/index',
pathMatch:'full'
},
{
path: 'index',
component:Tab1Component
},
{
path: 'secound',
component:Tab2Component,
children:[
{
path: 'tab3',
component:Tab3Component
},
{
path: 'tab4',
component:Tab4Component
},
]
},
];
包含最外层路由的组件AppComponent中的html如下
<a [routerLink]="['/index']">首页</a>
<a [routerLink]="['/secound']" >同级页面</a>
<router-outlet></router-outlet>
AppComponent构造函数(这并非是路由组件)
import { Component,OnInit } from '@angular/core';
import {Router,NavigationEnd} from '@angular/router';;
import 'rxjs/add/operator/filter'
constructor(private router:Router){
router.events.filter(event=>event instanceof NavigationEnd).subscribe((event:NavigationEnd)=>{
if (event.url=="/index"){
alert("这是首页")
} else if(event.url.startsWith('/secound')){
alert("这不是首页")
}
})
}
监听路由
通过过滤获取事件然后监听路由的地址
event.url.startsWith(‘/secound’)表示的是路由开始为/secound的地址,即是包含它及其它的子路由
点击首页
点击同级页面
点击子路由