带有参数的Angular2路由失败 [英] Angular2 Routing with parameters fails

查看:119
本文介绍了带有参数的Angular2路由失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了麻烦(在非常意想不到的地方会发生各种错误),而我最好的猜测是发生这种情况的原因是路由的设置方式.

I am having troubles (all sorts of errors in very unexpected places) and my best guess is that it happens because of the way routing is set up.

这是我的 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 中,我有这段代码:

Then, in CalendarComponent.ts I have this piece of code:

 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),我可以通过直接在浏览器中键入其中任何一个来启动应用程序

Anyway, just a half year ago (some RC @Angular2) I could start the app by typing any of these directly into the browser

localhost:3000

localhost:3000/calendar

localhost:3000/calendar/2017-05-27

,将获得预期的结果.现在我已经localhost:3000开始,以便 app 将我引导通过../login-> ../calendar-> ../calendar/2017-05-27,否则我得到了各种麻烦,例如Cannot read property subscribe of nullCannot activate already activated outlet.

and would get expected results. Now I have to start from localhost:3000, so that the app routes me through ../login --> ../calendar --> ../calendar/2017-05-27, otherwise I get all sorts of troubles, like Cannot read property subscribe of null or Cannot activate already activated outlet.

我想,路由已经更新,我已经落后了.有什么帮助吗?

I guess, the routing has been updated and I am lagging behind. Any help on this, please?

推荐答案

订阅路由参数可能会有时间延迟,我建议您使用服务ActivatedRouteSnapshot

There might be a time delay in subscribing to the route params, I suggest you to use non-Observable option using the service ActivatedRouteSnapshot

注入服务ActivatedRouteSnapshot并使用

this.activatedRoute.route.snapshot.params.urlString

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

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

因为您的路线将按照定义的顺序通过,并尝试将参数1与上面的内容匹配

as your route will fall through in the order of definition and tries to match the param one with the above

这篇关于带有参数的Angular2路由失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆