javascript - Angular:在路由中传递可选数据
问题描述
我正在使用angular 5,我有一个很长的路由文件:
const homeRoutes: Routes = [
{
path: 'home', component: HomeComponent,
children: [
{
path: 'registration',
component: RegistrationComponent,
children: [
{
path: 'synthese',
component: SyntheseComponent
},
{
path: 'queue',
component: QueueComponent,
children: [
{
path: 'queue-modal',
component: QueueModalComponent
},
{
path: 'confirm',
component: ConfirmComponent
}
]
}
]
},
{
...
我想在“注册”路径中传递数据。
有人告诉我,我需要这样写: path: 'registration/:mydata'
,
然后订阅ActivatedRoute的数据
我并不总是传递数据的问题,它只是在某些情况下。
我怎样才能以最小的影响做到这一点?
解决方案
您可以使用查询字符串参数(AKA queryParams)代替路由参数。您不需要在路由中定义查询参数。
以下是相对 href 的示例:
registration/?mydata=123
这是您可以queryParams
为 a定义的方式routerLink
:
<a [routerLink]="['registration']" [queryParams]="{ mydata: 123 }">Go to Registration</a>
这是您可以读取该参数值的方式:
myValue: any;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.route.queryParams.subscribe(params => {
this.myValue = params['mydata'];
});
}
推荐阅读
- data-structures - 如何使用联合查找数据结构对字符串进行分组?
- r - 不使用 %>% 的不同值
- javascript - AngularJS单元测试时无法加载模块
- javascript - 是否可以在 React 中访问组件之外的函数?
- javascript - 将 Javsacript SDK 注入几个选定的页面
- git - 如何初始化,添加现有远程,然后在 Git 中推送新分支?
- c - 如何在一行中读取 C 中的多个字符串,每个字符串都包含空格?
- r - 创建列表时出现意外的符号错误
- scala - Spring Boot 2.2.4 升级后报错:scala error: "java.lang.NoSuchMethodError: scala.Predef$.refArrayOps([Ljava/lang/Object;)[Ljava/lang/Object;"
- java - 如何使用 Junit 和 Mockito 使用 Spring 存储库测试 void 方法