如何访问路由器中的参数?

时间:2020-10-01 10:52:51

标签: angular

如果要在某些页面上隐藏一些组件。但是我无法访问参数来从那里获取ID。

使用以下链接结构隐藏页面上的组件:

/ orders /:_ id

  constructor(
    private router: Router,
    private route: ActivatedRoute
  ) {
    this.ngUnsubscribe = this.router.events.subscribe(() => {
      this.currentRoute = router.url;
      console.log(this.route.snapshot.params);
      this.id = this.route.snapshot.params
      if (this.currentRoute == `/orders/${id}`) {
        this.isActive = true
      }
    });
  }
}

console.log(this.route.snapshot.params);

结果:

{}

4 个答案:

答案 0 :(得分:0)

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

constructor(private route: ActivatedRoute) {
    console.log(this.route.snapshot.params);
    console.log(this.route.snapshot.data);
    this.route.params.subscribe((pParams) => { // queryParams for url?id=1
        console.log(pParams);
        //console.log(this.route.snapshot.params);
        //console.log(this.route.snapshot.data);
        if (pParams._id) { // checking if id exists
           this.isActive = true; 
        } 
    });
}

答案 1 :(得分:0)

要访问当前的路线参数,您可以做的是

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

constructor(private route: ActivatedRoute) {
  this.route.params.subscribe((params) => {
    console.log(params._id); // There you get access to your parameters
  }):
}

答案 2 :(得分:0)

这是怎么做

这是一个示例代码

在component.ts

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


export class ClassName implements OnInit {
 rootUrl: string;
 id: number;
 currentRoute: string;

 constructor(public router: Router, private _activatedRoute: ActivatedRoute) { }

 ngOnInit(): void {
   this.currentRoute = router.url;
   this.rootUrl = this.router.url.split('/')[1];  // gets the base folder e.g shop in "localhost:4200/shop"


   this._activatedRoute.paramMap.subscribe(
     params=>{
       this.id = +params.get('id');  // grabs the query param "id". the "+" converts it to integer
   }
);

} }

假设您的网址看起来像“ localhost:4200 / shop / 1234” 并且要显示基于URL的组件,必须执行以下操作:

在component.ts中,创建公共字符串变量,例如“ currentRoute”

在构造函数中,创建一个将保存url属性的Router实例和ActivatedRoute实例。如我的示例代码所示,使用ActivatedRoute实例从url获取查询参数并将其分配给变量。

然后在component.html文件中,向标签添加ngIf条件,以确定是否显示该组件

<app-product-header *ngIf="id > 0"></app-product-header>

答案 3 :(得分:0)

嗨,欢迎来到堆栈溢出。 对于您的问题,您以错误的方式使用了params对象。 route.params仍然是可观察的,这意味着您需要订阅它才能使用它。

关于用法,现在有两种方法可以从网址中检索参数。

1。使用可观察的

this.route.params.subscribe(param => {
    this.id = param._id;

    if (this.currentRoute == `/orders/${this.id}`) { // better use regex match or a better condition here
        this.isActive = true;
      }
});

2。使用paramMap对象

this.id = this.route.snapshot.paramMap.get('_id');

if (this.currentRoute == `/orders/${this.id}`) { // better use regex match or a better condition here
    this.isActive = true;
}

其他说明: 由于我看不到this.currentRoute的填充方式,因此我认为最好使用 .substring() .match() .indexOf()函数来确定URL中是否存在字符串(order / $ {this.id}),而不是使用特定的字符串。