1

我的应用中有两条路线

{path: 'activity/?cInfo=askjdfkajsdfkasd', component: PostComponent},
{path: 'activity/:id', component: PostDetailComponent}

我必须做些什么才能让它们工作?

带有查询字符串?cInfo=askjdfkajsdfkasd的路由应该转到PostComponent

和 Route 之类的活动/skjdfhakjdfhaajsdf应该转到PostDetailComponent

我试过

{path: 'activity/?cInfo=askjdfkajsdfkasd', component: PostComponent,canActivate:[CheckForListPage],pathMatch:'full'},
{path: 'activity/:id', component: PostDetailComponent,canActivate:[CheckForDetailPage]}

但每次调用 1。守卫返回布尔值。

角度是否像大多数 MVC 那样区分 queryParams 和 pathVariables?

4

1 回答 1

2

我认为您必须以这种方式声明您的路线。

{path: '/activity', component: PostComponent,canActivate:[CheckForListPage]},
{path: '/activity/:id', component: PostDetailComponent,canActivate:[CheckForDetailPage]}

因此,当您导航到/activity?cInfo=askjdfkajsdfkasd 时,路由器将与第一个定义的路由 (/activity) 匹配,然后您可以检索传递给组件内部路由的queryParameters (PostComponent)

ngOnInit(): void {
    this.route.queryParams
        .subscribe(params => {
          // complete params object
          console.log(params);

          // your param passed 
          console.log(params['cInfo'])
        });
}

当然你需要 import @angular/route ActivatedRoute

import { ActivatedRoute } from '@angular/router';

并在您的构造函数中将 route 设置为第一个代码片段之前的ActivatedRoute类型的属性(应该在组件类的 ngOnInit 方法中,这意味着您的组件类必须从 @angular/core 实现 OnInit)。

constructor(
    private route     : ActivatedRoute
){}
于 2017-02-10T17:44:22.780 回答