从 Angular 路由器模块中访问 :id 属性
Access :id property from within Angular router module
奇怪的问题,但是是否可以从 angular 路由模块本身访问 :id 属性?我有一条带有 child 的路由(例如,test/:id),我正在尝试使用路径中的 :id 属性 在我的 [=15] 的数据部分中设置标题属性=] 路线。这可能吗?会不会像将变量设置为当前 url 并使用该变量作为标题?提前致谢!
试试这个
constructor(private route: ActivatedRoute) {}
const id = this.route.snapshot.params['id'];
从您的 child,您可以访问 parent 的 :id,如下所示:
constructor(private activatedRoute: ActivatedRoute) {
}
const id = this.activatedRoute.parent.snapshot.params['id'];
上面给出的两种方法作为答案是可行的,但是如果您在 url 中更改 id 而在同一条路线上,它们将失败。请改用它。
constructor(private routeSnapshot: ActivatedRouteSnapshot) {
}
public routeSubscription: Subscription;
public id: any
ngOnInit() {
this.routeSubscription = this.routeSnapshot.paramMap.subscribe((dataMap) => {
this.id = dataMap.get('id');
});
}
ngOnDestroy() {
if(this.routeSubscription) {
this.routeSubscription.unsubscribe();
}
}
奇怪的问题,但是是否可以从 angular 路由模块本身访问 :id 属性?我有一条带有 child 的路由(例如,test/:id),我正在尝试使用路径中的 :id 属性 在我的 [=15] 的数据部分中设置标题属性=] 路线。这可能吗?会不会像将变量设置为当前 url 并使用该变量作为标题?提前致谢!
试试这个
constructor(private route: ActivatedRoute) {}
const id = this.route.snapshot.params['id'];
从您的 child,您可以访问 parent 的 :id,如下所示:
constructor(private activatedRoute: ActivatedRoute) {
}
const id = this.activatedRoute.parent.snapshot.params['id'];
上面给出的两种方法作为答案是可行的,但是如果您在 url 中更改 id 而在同一条路线上,它们将失败。请改用它。
constructor(private routeSnapshot: ActivatedRouteSnapshot) {
}
public routeSubscription: Subscription;
public id: any
ngOnInit() {
this.routeSubscription = this.routeSnapshot.paramMap.subscribe((dataMap) => {
this.id = dataMap.get('id');
});
}
ngOnDestroy() {
if(this.routeSubscription) {
this.routeSubscription.unsubscribe();
}
}