如何读取组件 angular 中路由 url 中传递的数据
How to read data passed in routed url in component angular
我是 angular 2+ 的新手,正在努力学习。
我在angular有一条路线,比如
const routes: Routes = [{path:"home",component:HomeComponent},
{path:"designer",component:DesignerComponent},
{path:"designer/:id",component:DesignerComponent}];
使用路径 designer/:id
到达 DesignerComponent
后,我想获取值 "id"。我怎样才能做到这一点?我正在使用最新版本的 angular.
你需要添加ActivatedRoute,里面会有snapshot.paramMap你会得到你传递的参数。
import {ActivatedRoute} from '@angular/router';
import {OnInit} from '@angular/core';
private userId = '';
constructor(private route: ActivatedRoute){
}
ngOnInit() {
this.userId = this.route.snapshot.paramMap.get('id');
}
或
ActivatedRoute.paramMap 属性是路由参数的Observable map。当用户导航到组件时,paramMap 会发出一个包含 id 的新值映射。在 ngOnInit 中,您订阅这些值并设置 ID。
ngOnInit() {
this.route.paramMap.pipe(
switchMap(params => {
// (+) before `params.get()` turns the string into a number
this.userId = +params.get('id');
})
);
}
你可以通过两种方式首先是
constructor(private route: ActivatedRoute){
this.userId=this.route.params.snapshot['id']
}
您可以通过其他方式订阅参数,例如
constructor(private route: ActivatedRoute){
this.route.params.subscribe(data=>this.userId=data['id']
})
}
如果您的参数可以在同一根目录下更改,请使用第二种方法
最好订阅路由,这样每次 /:id
变化时你都能得到值。
在DesignerComponent
class的构造函数中添加这段代码:
constructor(private route: ActivatedRoute){
this.route.params.subscribe(data => this.userId = data['id'])
});
我是 angular 2+ 的新手,正在努力学习。
我在angular有一条路线,比如
const routes: Routes = [{path:"home",component:HomeComponent},
{path:"designer",component:DesignerComponent},
{path:"designer/:id",component:DesignerComponent}];
使用路径 designer/:id
到达 DesignerComponent
后,我想获取值 "id"。我怎样才能做到这一点?我正在使用最新版本的 angular.
你需要添加ActivatedRoute,里面会有snapshot.paramMap你会得到你传递的参数。
import {ActivatedRoute} from '@angular/router';
import {OnInit} from '@angular/core';
private userId = '';
constructor(private route: ActivatedRoute){
}
ngOnInit() {
this.userId = this.route.snapshot.paramMap.get('id');
}
或
ActivatedRoute.paramMap 属性是路由参数的Observable map。当用户导航到组件时,paramMap 会发出一个包含 id 的新值映射。在 ngOnInit 中,您订阅这些值并设置 ID。
ngOnInit() {
this.route.paramMap.pipe(
switchMap(params => {
// (+) before `params.get()` turns the string into a number
this.userId = +params.get('id');
})
);
}
你可以通过两种方式首先是
constructor(private route: ActivatedRoute){
this.userId=this.route.params.snapshot['id']
}
您可以通过其他方式订阅参数,例如
constructor(private route: ActivatedRoute){
this.route.params.subscribe(data=>this.userId=data['id']
})
}
如果您的参数可以在同一根目录下更改,请使用第二种方法
最好订阅路由,这样每次 /:id
变化时你都能得到值。
在DesignerComponent
class的构造函数中添加这段代码:
constructor(private route: ActivatedRoute){
this.route.params.subscribe(data => this.userId = data['id'])
});