如何在Angular 2中跟踪路由?

OPV*_*OPV 29 angular-routing angular

我有分离文件路由设置的组件:

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 { }
Run Code Online (Sandbox Code Playgroud)

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

如何在Angular 2中跟踪路由?

dev*_*qon 53

您可以 使用选项传入第二个参数:

imports: [
    RouterModule.forRoot(
      routes,
      { enableTracing: true } // <-- debugging purposes only
    )
]
Run Code Online (Sandbox Code Playgroud)

  • 我在控制台看不到任何东西 (9认同)
  • 在哪里可以看到日志信息? (2认同)
  • 在浏览器的控制台中 (2认同)
  • 这帮助我调试组件模板的问题。我点击了一个链接,但什么也没发生,控制台上也没有任何迹象。只需添加此选项就会在控制台上产生非常详细且有用的“NavigationError”事件。 (2认同)

Tom*_*Tom 16

正如最被接受的答案中的评论所暗示的那样,这enableTracing在该forChild方法中不起作用。一个简单的解决方法是订阅所有路由事件,AppModule如下所示:

export class AppModule {

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

}
Run Code Online (Sandbox Code Playgroud)


Wou*_*pen 8

除了 devqons 之外,还有一个很好的答案:如果您暂时注释掉通配符路由,那么调试您的路由定义将会容易得多。通配符路由在生产中很方便显示组件NotFound,但在调试时却很痛苦。

例如:

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

    // If you have a catch-all route defined, outcomment is like below
    // {
    //     path: '**',
    //     redirectTo: '/error/not-found',
    // },
];
Run Code Online (Sandbox Code Playgroud)

在对您的包罗万象的路由进行注释后,路由器将不会吞掉您的错误,并在浏览器控制台中准确显示哪些路由无法与您的定义匹配。

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

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)
Run Code Online (Sandbox Code Playgroud)

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


Pan*_*ash 5

虽然我回答这个问题已经晚了。但它对于 Angular 新手来说可能会有用。

有两种方法可以跟踪角度路线的变化

1.RouterModule(启用跟踪)

您可以设置enableTracing记录RouterModule所有路线更改事件。

RouterModule.forRoot(routes, { 
  enableTracing: true,    /* <-- Set this to true */
}),
Run Code Online (Sandbox Code Playgroud)

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();
    });
}
Run Code Online (Sandbox Code Playgroud)