如何在 Angular 中使用快照或 ActivatedRoute 订阅者从 URL 获取 id? [英] How to get id from the URL using snapshot or ActivatedRoute subscriber in Angular?
问题描述
我使用快照方法获取价值,但它在类"之后获取价值在这种情况下 20 但我需要 33 路径像得到
credits/33/classes/20 only 20 or credits/33/classes/only null("")
更新:我找到了解决问题的方法.
现在可以正确获取 id.错误是访问了右子组件中的元素,在 Snapshot 版本中的子组件 MatDialog 组件中不起作用.
构造函数(私有路由:ActivatedRoute){}ngOnInit(): 无效 {console.log(parseInt(this.route.snapshot.paramMap.get('id1')));
<块引用>
如果你的 url 有 2 个 Id 值,你可以使用 route.parent 的快照
console.log(parseInt(this.route.parent.snapshot.paramMap.get('id1')));}
你在路由模块中的路径是
const appRoutes: Routes = [{ path: 'credits/:id1/classes/:id2', 组件: YourComponent }];
假设 id1 是 33 并且id2 是 20
代码将是:使用 ActivatedRoute 而不是 ActivatedRouteSnapshot
import { ActivatedRoute } from '@angular/router';构造函数(私有路由:ActivatedRoute){ngOnInit() {this.route.params.订阅((参数:参数)=>{this.id1 = +params['id1'];this.id2 = +params['id2'];console.log(id1 + '' + id2);});}}
I am getting value using snapshot method but it is getting the value after "classes" in this case 20 but I need 33 path like getting
credits/33/classes/20 only 20 or credits/33/classes/ only null("")
Update: I found a solution to my question.
Now it is getting id properly. The mistake is accessing to element in the right child component, didn't work in child's MatDialog component within the Snapshot version.
constructor(private route: ActivatedRoute) {}
ngOnInit(): void {
console.log(parseInt(this.route.snapshot.paramMap.get('id1')));
If your url has 2 Id values, you can use snapshot of route.parent
console.log(parseInt(this.route.parent.snapshot.paramMap.get('id1')));
}
your path in routing module will be
const appRoutes: Routes = [
{ path: 'credits/:id1/classes/:id2', component: YourComponent }];
suppose id1 is 33 and id2 is 20
the code will be: use ActivatedRoute instead of ActivatedRouteSnapshot
import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute) {
ngOnInit() {
this.route.params
.subscribe(
(params: Params) => {
this.id1 = +params['id1'];
this.id2 = +params['id2'];
console.log(id1 + '' + id2);
}
);
}
}
这篇关于如何在 Angular 中使用快照或 ActivatedRoute 订阅者从 URL 获取 id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!