angular - 重定向页面而不使用Angular5中的组件
问题描述
登录或注册后,我想创建一个类来确定经过身份验证的用户的角色并将他重定向到正确的页面。有没有另一种方法来做到这一点而不是使用角度组件?我不喜欢组件页面的是页面在重定向之前加载,即使组件没有显示任何内容,它仍然使用来自 app.component 的基本模板。
我正在使用 Keycloak 进行注册和登录(这意味着它不是我正在开发的应用程序的一部分,我只能设置 redirectUri)。所以我只能重定向到一个 URL。
解决方案
这是我在这个案例中使用的总体思路。
创建一个具有空白模板 (.html) 的登录组件。
确保也为其设置路由。
app.routing.ts
{ path: '', redirectTo: '/login', pathMatch: 'full' },
{ path: 'login', component: LoginScreenComponent},
登录屏幕.component.ts
constructor(private keyCloakService: KeyCloakService, private router: Router) {}
ngOnInit() {
// Do a call where you get logged in user and it's role, ex:
let role = this.keyCloakService.getUserRole();
// Do a redirect based on that role
if(role == "admin){
this.router.navigate(["/admin"]);
}
}
一旦你得到这个工作,我还建议将AuthGuard添加到你的角色路由中。
您还可以采用第二种更简洁的方法,但如果您之前没有使用过 AuthGuard,那么会稍微复杂一些。
简而言之,您将处理我在您的 AuthGuard 服务中为您提供的解决方案。这样您将避免创建登录组件,但结果将是相同的。
而关于app.component.ts的模板,通常的做法是你只有<router-outlet></router-outlet>
在里面,所以你不加载任何布局,你有更多的自由。
编辑(回答下面的问题): 您可以通过路由使用您的安全和非安全布局。例如:
{
path: 'admin',
component: AdminLayoutComponent,
canActivate: [Guard],
children: [
{
path: '',
loadChildren: './components/app-admin/secure.module#SecureModule'
}
]
}
并对公共布局做同样的事情。这样,您将只在您的 app.component 中拥有,并且将有更多的重定向自由等。
推荐阅读
- android - 是否可以有两个单独的帐户来获取单个应用程序的 firebase crashlytics
- c# - 如何从消息中正确创建类
- dafny - Dafny 中 multiset(a[..a.Length]) 和 multiset(a[..]) 之间的区别
- erlang - 将 Map 作为参数传递给函数并获取 Erlang 中的值的键
- ios - iOS系统标签在明暗模式下的颜色代码是什么?
- facebook - Blazor WebAssembly 使用后端身份 Api 和社交提供程序进行身份验证
- reactjs - 我在开玩笑中使用 toHaveBeenCalled() 时遇到错误?
- java - 异常运行应用程序 application.TipCalculator
- java - 使用 Test Kit 测试自定义 Gradle 插件
- intellij-idea - 我想知道 IntelliJ IDEA 的默认字体