【发布时间】:2021-07-12 21:26:35
【问题描述】:
我正在编写一个具有以下结构的模拟电子商务应用程序:
- 应用程序
- 认证
- 登录页面
- 注册页面
-
auth-routing.module.ts
const routes: Routes = [ { path: 'signup', component: SignUpPage, }, { path: 'signin', component: SignInPage, }, ]; - auth.module.ts
- 管理员
- 根页面
-
admin-routing.module.ts
const routes: Routes = [ { path: 'admin', component: RootPage, children: [ // ... ], }, ]; - admin.modules.ts
- 客户
- 根页面
- 目录页
- 结帐页面
- 感谢页面
-
customer-routing.module.ts
const routes: Routes = [ { path: 'customer', component: RootPage, children: [ { path: 'catalog/:categoryId', component: CatalogPage }, { path: 'checkout', component: CheckOutPage }, { path: 'thankyou', component: ThankYouPage }, ], }, ]; - customer.module.ts
- 页面未找到
-
app-routing.module.ts
const routes: Routes = [ { path: '**', component: NotFoundPage }, ]; - app.module.ts
- app.component.html
- app.component.css
- 认证
基本的工作流程应该如下:
- 用户导航到根路径
/。 - 应用程序检测到他们没有登录,因此将他们重定向到
/signin。 - 他们输入凭据并按登录。
- 如果认证成功,
- 如果用户是管理员,他们会被重定向到
/admin。-
admin-router.module.ts将它们重定向到/admin的某个子路径。
-
- 如果用户是客户,他们会被重定向到
/customer。-
customer-router.module.ts将他们重定向到/customer/catalog/<default category ID>。 - 他们将一些产品放入购物车,然后前往
/customer/checkout。 - 他们下订单并被重定向到
/customer/thankyou。
-
- 如果用户是管理员,他们会被重定向到
我不确定如何在成功登录后完成重定向。显然它必须分两个阶段完成:首先到一些公共路径,例如/,然后到/customer 或/admin,具体取决于用户的角色。第二阶段可能需要app-routing.module.ts处理,可能需要使用警卫,但我不确定具体该怎么做。
编辑 (2021-04-20)
问题可以总结如下:
我需要一种方法(最好是声明性的)将应用程序从 / 重定向到以下路径之一,具体取决于其状态:
| State | Path |
|---|---|
| Logged out | /auth |
| Logged in as a customer | /customer |
| Logged in as an admin | /admin |
【问题讨论】:
-
对于第二部分,我认为您最好使用
resolver,它将返回您需要的数据。 -
在用户通过身份验证后,为什么不直接使用 router.navigate 到 /admin 或 /customer?
-
@c_froehlich 显然这会起作用,但它会在登录页面和应用程序的其余部分之间产生不良耦合。从理论上讲:无论如何,我需要将已登录用户的请求重定向到
/customer或/admin,因此对于用户刚刚完成的情况,没有理由单独实现此重定向已登录。 -
@RonInbar 我明白了。通常我定义一个发射器,只要用户“状态”发生变化(登录、注销),它就会触发下一个事件。 “InitialPageService”可以订阅此事件并进行重定向。这样它就不会绑定到特定的路线。
标签: angular authentication angular-routing user-roles angular-guards