我请求创建一个用户可以填写的表格。另外还应考虑拒绝访问和未经授权的访问。独立使用。由于应用程序组件是程序入口点,我在 ngOnInit() 中检查这些。
app.routes.ts
export const routes: Routes = [
{
path: '',
component: AppComponent,
},
{
path: 'accesserror',
component: AccessDenyComponent,
},
]
访问拒绝.component.ts
@Component({
selector: 'app-access-deny',
standalone: true,
imports: [],
templateUrl: './access-deny.component.html',
styleUrl: './access-deny.component.css'
})
export class AccessDenyComponent {
}
app.component.ts(代码片段)
async ngOnInit() {
...
if(!ret) {
this.router.navigate([?]);
}
this.buildForm();
this.setupForm();
}
如何显示错误页面?
首先创建 home 组件并使其成为默认路由
{ 小路: '', 组件:HomeComponent, }
你可以使用守卫来实现这一点,这是一个解释的链接 https://angular.io/api/router/CanActivate
使用此命令 ng g g myguard 创建守卫。
要检查用户是否可以使用我称之为帐户的服务访问您的主页,请在 isAuthenticated() 方法中实现逻辑
export const myguard: CanActivateFn = (路线, 状态) => { const accountService = 注入(AccountService); const 路由器 = 注入(路由器); 如果(accountService.isAuthenticated()){ 返回真; } 别的 { accountService.redirectUrl = state.url; return router.createUrlTree(['/accesserror'], {queryParams:{returnUrl: state.url}}); } };
以及路由模块`
{路径:'',组件:HomeComponent,canActivate:[myguard]},
`