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)
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)
除了 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”存在问题。
虽然我回答这个问题已经晚了。但它对于 Angular 新手来说可能会有用。
有两种方法可以跟踪角度路线的变化。
您可以设置enableTracing
记录RouterModule
所有路线更改事件。
RouterModule.forRoot(routes, {
enableTracing: true, /* <-- Set this to true */
}),
Run Code Online (Sandbox Code Playgroud)
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)
归档时间: |
|
查看次数: |
15499 次 |
最近记录: |