带参数的Angular2路由失败

时间:2017-05-27 20:49:35

标签: angular typescript angular2-routing angular-component-router

我遇到了麻烦(在非常意想不到的地方出现了各种各样的错误),我最好的猜测是因为路由设置的方式而发生。

这是我的 app-routing.module.ts

const appRoutes: Routes = [
  { path: 'calendar', component: CalendarComponent, canActivate: [AuthGuard] },
  { path: 'calendar/:urlString', component: CalendarComponent, canActivate: [AuthGuard] },
  { path: 'myprofile', component: ProfileComponent, canActivate: [AuthGuard] },
  { path: 'profiles', component: ProfileComponent, canActivate: [AuthGuard] },
  { path: 'locations', component: LocationComponent, canActivate: [AuthGuard] },
  { path: 'login', component: AuthComponent },
  { path: '',   redirectTo: '/login', pathMatch: 'full' }
];

@NgModule({
  imports: [ RouterModule.forRoot(appRoutes) ],
  exports: [ RouterModule ]
})

然后,在 CalendarComponent.ts 中,我有这段代码:

 imports (...)

 constructor(
   private activatedRoute: ActivatedRoute,
 ){
 }

 public ngOnInit(): void {
    this.activatedRoute.params.subscribe((params: Params) => {
        this.resolveURLParams(params);
    });
  }

  public resolveURLParams( params ): void {

    // do stuff based on params

  }

无论如何,就在半年前(一些RC @ Angular2)我可以通过直接在浏览器中输入任何这些来启动应用程序

localhost:3000

localhost:3000/calendar

localhost:3000/calendar/2017-05-27

并获得预期的结果。现在我 localhost:3000开始,以便应用通过../login - >路由我../calendar - > ../calendar/2017-05-27,否则我会遇到各种麻烦,例如Cannot read property subscribe of nullCannot activate already activated outlet

我想,路由已更新,我落后了。对此有任何帮助吗?

2 个答案:

答案 0 :(得分:1)

订阅路线参数可能有时间延迟,我建议你使用服务ActivatedRouteSnapshot使用非Observable选项

注入服务ActivatedRouteSnapshot并使用

获取参数
this.activatedRoute.route.snapshot.params.urlString

注意:使用pathMatch:full作为定义

{ path: 'calendar', component: CalendarComponent, canActivate: [AuthGuard] , pathMatch:'full'},

因为您的路线将按照定义的顺序落实,并尝试将参数与上述

匹配

答案 1 :(得分:0)

这实际上是一个无赖,但是没有问题与路由和ActivatedRoute订阅的工作方式。问题在于我使用的AuthGuard,它被破坏了。现在我已经修好了后卫,所有的问题都消失了。所以,谢谢你试图提供帮助。