angular - How to use params property of ActivatedRouteSnapshot to populate data differently in a component
问题描述
Imagine a situation where we have a single component which has to be populated with data differently based on different url parameters coming in.
That is, consider the below url patterns:
1. http://localhost:4200/venues/5760665662783488
2. http://localhost:4200/users/2gjmXELwGYN6khZgzaeWKmLtIDt2
3. http://localhost:4200/revenue
Within the component, If i use ActivatedRouteSnapshot interface to log the parameters of my incoming urls, i get below results:
1. {venueid: "5760665662783488"}
2. {userid: "2gjmXELwGYN6khZgzaeWKmLtIDt2"}
3. {}
Now, if i want to populate fields of my single component in three different ways based on the three different url parameters like above, how can do so?
I mean how can i populate differently for incoming venueid/userid/{}? Is there a method on the ActivatedRouteSnapshot interface to check the key of the params object?
I tried looking through the documentation for ActivatedRouteSnapshot interface but did not find an answer.
Snip of my code to log the url params:
console.log(this.activatedRoute.snapshot.params);
I would like to learn different ways to achieve this functionality if there exist few. Thanks in advance.
解决方案
Well the ActivatedRouteSnapshot
has a paramMap
property and the ParamMap
class has the .has(paramName)
method for this.
if(myActivatedRouteSnapshot.paramMap.has('userid')) {
...
}
Where myActivatedRouteSnapshot
is the ActivatedRouteSnapshot
you speak of.
https://angular.io/api/router/ActivatedRouteSnapshot#paramMap https://angular.io/api/router/ParamMap
推荐阅读
- core-data - CoreData 的可观察对象 - 'NSSet?' 类型的值 没有下标
- python - 通过函数迭代列表不断返回 Nonetype
- postgresql - Postgres有条件地检索值?
- r - 如何缩短 clusterprofiler 的名称?
- flutter - 为什么我们在 Flutter 中需要无状态小部件?
- c# - 如何仅为一个 Razor 页面设置 `ValidationVisitor.MaxValidationDepth` = 1?
- python - 如果多列包含特定值,则删除熊猫数据框中的一行
- node.js - Nodejs TypeError“不是构造函数”
- graphics - 从 3D 模型(网格)获取边缘点
- php - 在 laravel 中插入数组数据