angular路由事件,路由监测地址

路由配置文件

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的地址,即是包含它及其它的子路由
点击首页
这里写图片描述
点击同级页面
这里写图片描述
点击子路由
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值