【发布时间】:2022-09-29 20:02:43
【问题描述】:
我希望能够导航到同一个组件(详细信息组件) 来自其他 2 个不同的组件(Home 和 CategoryAppsComponent),并根据导航的来源更改基于标志/布尔属性的几个 UI 元素。
我使用 Router 导航方法的 state 属性让它工作,如下所示:
分别在导航发生的 Home.ts 和 CategoryAppsComponent.ts 上:
this.router.navigate([\"home\", \"details\", id], { state: { categoryAppsHeader: false } });
this.router.navigate([\"home\", \"details\", id], { state: { categoryAppsHeader: true } });
然后在 Details Component.ts 上将值分配给一个道具,然后在相应的 HTML 上使用 ngIf 来显示或隐藏标题:
this.categoryAppsHeader = this.router.getCurrentNavigation().extras.state[\"categoryAppsHeader\"]
这是我找到的解决方案,因为虽然 DetailsComponent 是 HomeComponent 在路由上的直接子级,但 CategoryAppsComponent 不是,所以我不能只通过 HTML 传递属性。
然而,这产生了一个问题 - 当我点击其中一张卡片时详细信息组件(请参阅下面的 routes.ts 文件),从主页或 CategoryAppsComponent 刷新页面,Angular 将我发送到主页,就好像路由不存在一样(示例路由可能是 localhost :4200/家/详情/123)。
我想这与 state 属性有关,因为在我实现它之前,我已经进行了刷新工作。
下面的最后一条路线是我试图让它与 data 道具一起工作,但我没有成功,我把它留在了,因为也许有人知道使用它的解决方案。
路线.ts
export const routes: Route = {
path: `home`,
component: HomeComponent,
children: [
{
path: \"details/:id\",
component: DetailsComponent,
},
{
path: \"categories\",
children: [
{
path: \"\",
pathMatch: \"full\",
component: CategoriesComponent,
},
{
path: \":categoryId/apps\",
component: CategoryAppsComponent,
},
{
path: \"apps/:appId\",
component: DetailsComponent,
data: {
categoryAppsHeader: true,
},
],
},
],};
如果解释有点混乱或者我没有提供足够的信息,我很抱歉,如果您对实施有任何疑问,请告诉我,希望您能帮助我。任何帮助表示赞赏,谢谢:)
-
坦率地说,我被解释弄糊涂了。 StackBlitz 肯定会有所帮助。
标签: angular typescript angular-routing angular-router angular12