gpt4 book ai didi

javascript - 动态创建路线

转载 作者:行者123 更新时间:2023-12-02 22:56:08 26 4
gpt4 key购买 nike

我的应用程序有一些 Angular 色,例如学生、教师等。我的路线定义为

const routes : Routes = [
{ path : '', component : StudentDashboard }
]

我想知道是否可以根据 Angular 色动态地将 StudentDashboard 替换为 TeacherDashboard。有关 Angular 色的数据存在于服务中。

我试过了

const routes : Routes = [
{ path : '', component : true ? StudentDashboard : TeacherDashboard }
]

这没有给出任何编译错误。但是如何从服务中获取 Angular 色,以便可以替换三元表达式中的条件。

我不是在寻找的是1) 重新路由 2) 条件子组件我正在寻找操纵路线定义,我不知道是否可能,但尝试一下

最佳答案

为什么不将两条路径都放入路由模块中:

const routes : Routes = [
{ path : 'teacher', component : TeacherDashboard },
{path:'student', component : StudentDashboard}
];

当您导航时,您可以从服务中进行检查:

if(yourService.role === 'student') {
this.router.navigate(['/student']);
} else {
this.router.navigate(['/teacher']);
}

如果路径应该为空,那么你可以使用结构指令 ngIf ,例如:

<app-student *ngIf="role === 'student'"></app-student>
<app-teacher *ngIf="role === 'teacher'"></app-teacher>

在 component.ts 中,您可以从服务中获取 Angular 色:

role: string;
ngOnInit() {
this.role = yourservice.role;
}

关于javascript - 动态创建路线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57969505/

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