我正在寻找在我的AppComponent中检测路由变化。

然后,我将检查全局用户令牌,以查看用户是否已登录,以便在用户未登录时重定向该用户。


当前回答

简单的答案 角8。*

constructor(private route:ActivatedRoute) {
  console.log(route);
}

其他回答

RxJS 6

router.events.pipe(filter(event => event instanceof NavigationStart))

感谢Peilonrayz(见下面的评论)

new router >= RC.3

import { Router, NavigationStart, NavigationEnd, NavigationError, NavigationCancel, RoutesRecognized } from '@angular/router';

constructor(router:Router) {
  router.events.forEach((event) => {
    if(event instanceof NavigationStart) {
    }
    // NavigationEnd
    // NavigationCancel
    // NavigationError
    // RoutesRecognized
  });
}

你也可以通过给定的事件进行过滤:

import 'rxjs/add/operator/filter';

constructor(router:Router) {
  router.events
    .filter(event => event instanceof NavigationStart)
    .subscribe((event:NavigationStart) => {
      // You only receive NavigationStart events
    });
}

使用成对操作符来获取先前和当前事件也是一个不错的想法。https://github.com/angular/angular/issues/11268#issuecomment-244601977

进口的rxjs /添加/运营商/成对的; import {Router} from '@angular/ Router '; 导出类AppComponent { 构造函数(私有路由器:router) { This.router.events.pairwise ().subscribe((event) => { console.log(事件); }); }; }

只需在AppRoutingModule上进行更改

@NgModule({
imports: [RouterModule.forRoot(routes, { scrollPositionRestoration: 'enabled' })],
  exports: [RouterModule]
})

简单的答案 角8。*

constructor(private route:ActivatedRoute) {
  console.log(route);
}

角8。检查当前路由是否为基路由。

  baseroute: boolean;
  constructor(
    private router: Router,
  ) {
    router.events.subscribe((val: any) => {
      if (val.url == "/") {
        this.baseroute = true;
      } else {
        this.baseroute = false;
      }
    });
  }

位置的作品……

import {Component, OnInit} from '@angular/core';
import {Location} from '@angular/common';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent implements OnInit {

    constructor(private location: Location) {
        this.location.onUrlChange(x => this.urlChange(x));
    }

    ngOnInit(): void {}

    urlChange(x) {
        console.log(x);
    }
}