如何使用 ActivatedRouteSnapshot 的参数 属性 在组件中以不同方式填充数据

How to use params property of ActivatedRouteSnapshot to populate data differently in a component

想象一下我们有一个组件的情况,它必须根据传入的不同 url 参数以不同方式填充数据。

也就是说,考虑以下 url 模式:

1. http://localhost:4200/venues/5760665662783488 
2. http://localhost:4200/users/2gjmXELwGYN6khZgzaeWKmLtIDt2 
3. http://localhost:4200/revenue 

在组件中, 如果我使用 ActivatedRouteSnapshot 接口来记录我传入的 urls 的参数,我得到以下结果:

1. {venueid: "5760665662783488"}
2. {userid: "2gjmXELwGYN6khZgzaeWKmLtIDt2"}
3. {}

现在,如果我想根据上述三个不同的 url 参数以三种不同的方式填充我的单个组件的字段,该怎么做?

我的意思是如何为传入的 venueid/userid/{} 填充不同的内容? ActivatedRouteSnapshot 接口上是否有检查params 对象的key 的方法?

我尝试查看 ActivatedRouteSnapshot 接口的文档,但没有找到答案。

用于记录 url 参数的代码片段: console.log(this.activatedRoute.snapshot.params);

如果没有的话,我想学习不同的方法来实现这个功能。提前致谢。

好吧,ActivatedRouteSnapshot 有一个 paramMap 属性,ParamMap class 有 .has(paramName) 方法。

  if(myActivatedRouteSnapshot.paramMap.has('userid')) {
    ...
  }

其中 myActivatedRouteSnapshot 是您所说的 ActivatedRouteSnapshot

https://angular.io/api/router/ActivatedRouteSnapshot#paramMap https://angular.io/api/router/ParamMap

您可以使用 paramMap property of the ActivatedRouteSnapshot which returns a ParamMap object that has also a property keys.

所以要记录您使用的参数键:

console.log(this.activatedRoute.snapshot.paramMap.keys);

我试过了..

const obj = this.activatedRoute.snapshot.params;
    if (Object.keys(obj)[0] === 'venueid') {
      console.log('venueid match'); // load venueid data for the component
    } else if(Object.keys(obj)[0] === 'userid') {
      console.log('userid match'); // load userid data for the component
    } else {
      console.log('other match'); // load other data for the component
    }

但是@AlesD 和@Robin De Schepper 的回答似乎更复杂。所以我会和他们一起去。