与params和获得params的角度路线

时间:2017-11-28 16:50:50

标签: angular angular-router

用户将点击此类电子邮件中的链接:

do-something/doSomething?thing=XXXXXXXXXXX

如何在路由器中定义路由并订阅获取参数?

目前在路由器中我有:

 {
  path: 'do-something/:id',
  component: DoSomethingComponent
 },

在组件中:

ngOnInit() {
 this.sub = this.route
  .params
  .subscribe(params => {
   console.log(params)
  });
}

但是,路线永远不会匹配。在重置密码作为参数后,“:id”不应该考虑什么吗?

2 个答案:

答案 0 :(得分:2)

这是我为角网站提供的那个

import { Component, OnInit }  from '@angular/core';
import { ActivatedRoute }     from '@angular/router';
import { Observable }         from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Component({
  template:  `
    <p>Dashboard</p>
    <p>Session ID: {{ sessionId | async }}</p>
  `
})
export class AdminDashboardComponent implements OnInit {

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
   //read query param
    this.route
      .queryParamMap
      .map(params => console.log(params.get('thing')););

     //read param value 
      this.route
      .paramMap
      .map((params: ParamMap) => 
                           console.log(params.get('id')));
  }
}

在这里阅读Routinh:https://angular.io/guide/router#!#optional-route-parameters

试试这个

const appRoutes: Routes = [
  { path: 'do-something/:id', component: DoSomethingComponent, name: 'Details'}];

现在导航如

this.router.navigate( [
  'Details', { id: 'idvalue', param1: 'value1'
}]);//this you can try from code

这场比赛

do-something/idvalue?param1=value1. //this try from browser

像这样阅读查询参数

ngOnInit() {
  // Capture the access token and code
  this.route
      .queryParams
      .subscribe(params => {
          let thing = params['thing'];
      });
}

或试试这个

(new URL(location)).searchParams.get("parameter_name")

答案 1 :(得分:0)

浪费了超过1个小时。

以下两项均无效:
  this.route.paramMap
  this.route.params

仅以下版本有效:
this.route.queryParams

1.URL就像这样:

http://localhost:4200/employee?tab=admin

2。需要提取查询参数tab的值,即admin

3。有效的代码是:

ngOnInit() {
   this.route.queryParams.subscribe(params => {
    console.error(" ==== ", params["tab"]); // this will print `admin`
    // this.tabNameFromUrl = params["tab"];
  });
}

希望有帮助。