【问题标题】:Angular2 Routing with parameters fails带有参数的Angular2路由失败
【发布时间】:2017-05-27 20:49:34
【问题描述】:

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

这是我的 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

我猜,路由已经更新,我落后了。请问这方面有什么帮助吗?

【问题讨论】:

  • 实际列出您看到的错误会对您有所帮助。
  • 如果我从 /calendar 开始,我会得到 错误:未捕获(承诺中):错误:无法激活已激活的插座。如果我从 /calendar/2017-05 开始,我得到 Error: Uncaught (in promise): TypeError: Cannot read property 'subscribe' of null at resolveUrlParams function
  • 嗯,我无法重现您的错误。能否提供一个可运行的 plnkr 示例?

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


【解决方案1】:

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

注入服务ActivatedRouteSnapshot并使用获取参数

this.activatedRoute.route.snapshot.params.urlString

注意:使用pathMatch:full 进行定义

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

因为您的路线将按照定义的顺序通过并尝试将参数一与上述匹配

【讨论】:

    【解决方案2】:

    这实际上很糟糕,但是路由和 ActivatedRoute 订阅的工作方式没有问题。问题出在我使用的 AuthGuard 上,它坏了。现在我已经修好了警卫,所有的问题都消失了。所以,感谢您的帮助。

    【讨论】:

      猜你喜欢
      • 2018-04-05
      • 2017-12-03
      • 2015-08-09
      • 2016-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-19
      • 2016-08-21
      相关资源
      最近更新 更多