【问题标题】:Angular navigate to same component from 2 different origins and display some different UI elements depending on navigation originAngular 从 2 个不同的来源导航到同一个组件,并根据导航来源显示一些不同的 UI 元素
【发布时间】: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


【解决方案1】:

回答以供将来参考,以防有人有同样的疑问并理解我的(坏的)解释:

我设法通过固定最后一条路线来做我想做的事:

{
    path: ":categoryId/apps/:id",
    component: DetailsComponent,
    data: {
        categoryAppsHeader: true
    }
},

然后继续详细信息组件的构造函数访问真的标记并将其存储在这样的变量中(并在模板上使用该布尔值):

this.categoryAppsHeader = this.activatedRoute.snapshot.data["categoryAppsHeader"];

P.S:一些奖励信息,我设法通过访问 URL 来实现“返回”按钮,将其拆分为一个数组并删除不需要的字符串:

this.router.navigate(window.location.pathname.split("/").slice(1, -1))

谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-07
    • 2017-01-04
    • 1970-01-01
    • 2016-11-16
    相关资源
    最近更新 更多