【问题标题】:Redirect to common error.component.html with Authguard使用 Authguard 重定向到常见的 error.component.html
【发布时间】:2022-01-15 12:23:09
【问题描述】:

我正在尝试使用 Guards 处理 Angular 中的错误。

我有一个 role.guard,它允许用户根据其角色进入某些路径。我也有一个 auth.guard 做同样的事情,但取决于授权。

角色守卫看起来像这样:

canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
    ): boolean {
        let res = route.data.role.includes(this.authService.getRole())
        if(!res){this.router.navigate(['/error'])}
        return res;
}

到目前为止,错误组件具有 {{message}} 属性,该属性在 error.component.ts 中声明。

我希望此属性包含取决于触发的 Guard 的错误消息(即,如果触发了 role.guard,则未授权,或者,例如,如果我有一个未找到组件的保护,则此页面不存在)。

我怎样才能做到这一点?有没有办法从 Guard 向错误组件发送消息并显示相应的错误?

【问题讨论】:

    标签: angular error-handling frontend angular-components angular-router-guards


    【解决方案1】:
    1. 第一个选项是使用query parameter,然后在component 中订阅它。在这种情况下,您的 URL 将受到影响。
    2. 第二个选项是添加一个新的错误服务并在模块中注册它。因此,您将拥有一个实例,您可以在其中添加将在防护和错误组件之间共享的属性。
    export class RoleGuard implements CanActivate {
        constructor(private _service: ErrorService) {...}
        public canActivate(...) {
            this._service.sharedValue = "something happened";
            ...
        }
    }
    
    export class ErrorComponent {
        constructor(private _service: ErrorService) {...}
        public ngOnInit(): void {
            console.log(this._service.sharedValue);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-30
      • 1970-01-01
      • 2012-11-18
      相关资源
      最近更新 更多