gpt4 book ai didi

Angular 2路由参数到数据

转载 作者:太空狗 更新时间:2023-10-29 17:37:03 24 4
gpt4 key购买 nike

我有一个带有 1 个参数的简单路由:

{
path: 'item/:id',
component: ItemComponent,
data: {title: 'Item detail'}
}

我在主 AppComponent 中使用数据标题属性设置页面标题:

export class AppComponent implements OnInit {
title: string;

ngOnInit() {
this.router.events
.. parse it
.subscribe((event) => {
this.title = event['title'];
});
}
}

然后我只是在 AppComponent 模板中显示它:

<h1>{{ title }}</h1>

问题是如果我想要动态标题,如 "Item detail #name(:id)"。有什么办法可以添加例如将参数(:id)或变量路由到数据标题属性中?有点像

{
path: 'item/:id',
component: ItemComponent,
data: {title: 'Item detail #' + :id }
}

最佳答案

正如我在评论中所说,您可以将 data.title 参数保留为蓝图,并从组件中替换动态部分。

路由声明:

{
path: 'item/:id',
component: ItemComponent,
data: { title: 'Item detail [id]' }
}

data.title 中,我编写了 [id] 以使替换更容易,但您可以随意使用您想要分隔要替换的字符串的任何符号。

然后,在组件中:

export class AppComponent {
title: string;

constructor(private route: ActivatedRoute) {}

ngOnInit() {
const titlePattern = this.route.snapshot.data['title'];
const id = this.route.snapshot.params['id'];
this.title = titlePattern.replace('[id]', id);
}
}

关于 Angular 2路由参数到数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42245928/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com