在Angular2中使用QueryParam处理路由

时间:2017-02-10 17:09:13

标签: angular angular2-routing angular2-cli angular2-router

我的appilcation中有两条路线

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

我需要做些什么才能让它们发挥作用?

使用查询字符串路径?cInfo = askjdfkajsdfkasd 应该转到 PostComponent

activity / skjdfhakjdfhaajsdf 之类的路线应该转到 PostDetailComponent

我试过

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

但每次调用1。警卫正在返回布尔值。

像大多数MVC那样,angularParams和pathVariables之间的角度是否区分?

1 个答案:

答案 0 :(得分: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'])
        });
}

当然你需要导入@ angular / route ActivatedRoute

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

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

constructor(
    private route     : ActivatedRoute
){}