gpt4 book ai didi

angular - 如何在本身通过主路由器 socket 提供服务的组件内使用 Angular 路由器 socket ?

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

我正在尝试制作 router-outlet在里面工作 DashboardComponent它本身是通过 router-outler 服务的出现在 app.component.html .

我想要实现的流程是这样的:

  • 用户登录后,用户被重定向到/dashboard这将加载 DashboardComponent .

  • DashboardComponent包含 mat-sidenav-containermat-sidenav链接和 div容器,我必须在其中提供不同的组件 - AComponent , BComponent , CComponent取决于在 mat-sidenav 中单击的链接.

即路径localhost:4200/dashboard/componentA应该显示 AComponentDashboardComponent的 div 容器等。

  • 路径 /dashboard应该重定向到 /dashboard/componentA

我很难弄清楚如何显示 DashboardComponent 中的组件使用 router-outlet .

这可能吗?有没有更好的方法来做到这一点?

Working code

**app.routing.ts**

import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { DashboardComponent } from './dashboard/dashboard.component';

import { AComponent } from './a/a.component';
import { BComponent } from './b/b.component';
import { CComponent } from './c/c.component';

export const appRoutes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'dashboard', component: DashboardComponent, outlet: 'dashboard',
children: [
{ path: '', component: AComponent },
{ path: 'componentA', component: AComponent },
{ path: 'componentB', component: BComponent },
{ path: 'componentC', component: CComponent }

]},

// otherwise redirect to home
// { path: '**', redirectTo: '' }
];

最佳答案

您所做的工作,只需进行一些修改。

首先,您不需要为仪表板组件内的路由器 socket 分配名称。命名 socket 有不同的用例,您可以阅读它们 here :

这里是你需要做的修改

  1. 从 app.routing.ts 中的仪表板路由中删除 outlet 属性
  2. 从 dashboard.component.html 中的 router-outlet 移除 name 指令
  3. 从标签 dashboard.component.html 中的 [routerLink] 中删除“dashboard/”。由于这些路线是当前激活路线的子路线,因此它们的路径将自动附加在仪表板之后。
//dashboard.component.html
<mat-sidenav #sidenav align="start" position="start" mode="side" opened="true" class="example-sidenav side-nav-style">
<ul>
<li>
<a [routerLink]="['componentA']">componentA</a>
</li>
<li>
<a [routerLink]="['componentB']">componentB</a>
</li>
<li>
<a [routerLink]="['componentC']">componentC</a>
</li>
</ul>
</mat-sidenav>
<div class="content">
<p>dashboard works!</p>
<router-outlet></router-outlet>
</div>

//app.routing.ts
children: [
// { path: '', component: AComponent },
{ path: 'componentA', component: AComponent },
{ path: 'componentB', component: BComponent },
{ path: 'componentC', component: CComponent },
{ path: '', redirectTo: 'componentA', pathMatch: 'full'}
]},

此外,请注意,我在子数组的第一行添加了注释,并在末尾用新的一行替换了它。使用这种方法,只要路径为空,它就会自动重定向到 componentA 并更改路由,而不是仅在空路径上显示 componentA。

Updated code

关于angular - 如何在本身通过主路由器 socket 提供服务的组件内使用 Angular 路由器 socket ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47074417/

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