如何在Angular 2 中跟踪路由?

How to trace routing in Angular 2?

我的组件带有单独的路由设置文件:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { Route } from '../core/route.service';
import { extract } from '../core/i18n.service';
import {CalendarThematicPlanComponent} from './calendar-thematic-plan.component';

const routes: Routes = Route.withShell([
  { path: 'calendar', component: CalendarThematicPlanComponent }
]);

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
  providers: []
})

export class CalendarThematicPlanRoutingModule { }

当我输入 URL 地址时:http://localhost:4200/calendar 我被重定向到主页。

如何在 Angular 2 中跟踪路由?

你可以传入a second argument with options:

imports: [
    RouterModule.forRoot(
      routes,
      { enableTracing: true } // <-- debugging purposes only
    )
]
根据文档,

Angular 然后会将所有事件记录到浏览器的控制台:

enableTracing?: boolean
When true, log all internal navigation events to the console. Use for debugging.

正如大多数接受的答案中的评论所暗示的那样,此 enableTracingforChild 方法中不起作用。一个简单的解决方法是订阅 AppModule 中的所有路由事件,如下所示:

export class AppModule {

  constructor(
    private readonly router: Router,
  ) {
    router.events
      .subscribe(console.log)
  }

}

除了 devqons 出色的答案:如果您临时 out-comment 通配符路由,调试路由定义会容易得多。通配符路由在生产中很方便,例如一个 NotFound 组件,但调试时很痛苦。

例如:

const routes: Routes = [
    ... (your route definions)

    // If you have a catch-all route defined, outcomment is like below
    // {
    //     path: '**',
    //     redirectTo: '/error/not-found',
    // },
];

在对您的 catch-all 路由进行注释后,路由器不会吞下您的错误并在您的浏览器控制台中准确显示无法与您的定义匹配的路由。

例如,当显示以下错误时:

core.js:4002 ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'projects/123'
Error: Cannot match any routes. URL Segment: 'projects/123'
    at ApplyRedirects.push../node_modules/@angular/router/fesm5/router.js.ApplyRedirects.noMatchError (router.js:2459)

您立即知道在路由定义中匹配 'projects/123' 存在问题。

虽然我来晚了回答这个问题。但它可能对 Angular.

的新手有用

您可以通过两种方式trace angular route changes

1。 RouterModule (enableTracing)

您可以将 enableTracing 设置为 RouterModule,这将记录您所有的路线更改事件。

RouterModule.forRoot(routes, { 
  enableTracing: true,    /* <-- Set this to true */
}),

2。订阅 Router.events

如果您不想跟踪所有路由器更改事件,那么您可以订阅 Router.events。您可以使用它来过滤特定的路线更改事件。

constructor(
  private router: Router,
  /* Other dependencies */
) {

  this.router.events
    .pipe(
      // You can also use traditional if else in the subscribe 
      filter(event => event instanceof NavigationStart)
    )
    .subscribe(event => {
      console.group(`Router event: ${event.constructor.name}`);
      console.log(event);
      console.groupEnd();
    });
}