如何从URL(路由)Angular 2获取参数?

时间:2017-12-06 14:25:23

标签: angular

我尝试在ngOnInit()中这样做:

ngOnInit() {
    this.route.queryParams
      .filter(params => params.type)
      .subscribe(params => {
        this.tab = params.type;
        this.setHeader();
      });
  }

我的网址是:

http://localhost:4200/s/6/t/p/create/1

路由是:

{path: ':Id/t/p/create/:type', component: CalendarComponent},

2 个答案:

答案 0 :(得分:3)

试试:

this.route.snapshot.params["page"]

页面是查询参数,因此路径必须像

const routes: Routes = [
  {
    path: 'page/:page',
    component: OrdersComponent,
    data: {
      title: 'Orders'
    }
  }
]

不要忘记将路由添加到构造函数

constructor(private route: ActivatedRoute) { }

和导入

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

答案 1 :(得分:0)

尝试

this.route.params.subscribe(params => {
    this.tab = params.type;
    this.setHeader();
  });