【问题标题】:Route to some other page based on guard in angular 6, rxjx 6 async request基于 Angular 6 中的守卫路由到其他页面,rxjx 6 异步请求
【发布时间】:2023-03-25 05:33:01
【问题描述】:

我已经实现了能够获取请求并控制页面授权的功能,我想在出现错误请求的情况下重定向到登录页面。

public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    return this.authSer.isAuthenticated().pipe(map((response) => {
            console.log('I ma here');
            if (response.status === 200) {
                return true;
            } else {
                console.log('Error getting data');
                return false;
            }
        }), catchError((error) => of(false))
    );
}

如何从这里路由到登录页面?我正在使用角度 6

【问题讨论】:

  • 注入路由器,调用router.navigate()。与您从其他任何地方导航的方式相同。你是否使用最新版本的 Angular,你也可以返回一个 Observable 而不是一个 Observable
  • 我是 Angular 新手,所以如果你能举例说明如何从 catchError 返回一个 observable
  • 你已经从 catchError 返回了一个 observable。
  • 我知道我正在抛出一个 observable,但假设我想在 catchError 打印一些值,我该怎么做
  • catchError(error => { console.log('hello'); return of(false); })。但这与你的问题有什么关系?你为什么要问这个问题,因为你已经在你的代码中使用了那个确切的语法?

标签: angular rxjs angular6 angular-guards


【解决方案1】:

我知道这个问题特别说明了 Angular 6,我只想提一下,从你的后卫的角度 7.1 You can return an UrlTree instead or a boolean 以及 PromiseObservable 等价物 - ,这将作为一个自动重定向。所以在你的情况下:

public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
  return this.authSer.isAuthenticated().pipe(
    map((response) => {
      console.log('I ma here');
      if (response.status === 200) {
        return true;
      } else {
        console.log('Error getting data');
        return false;
      }
    }),
    catchError((error) => of(false)),
    map(responseOk => {
      // Isolate dealing with true/false results since they can come from different opperators
      if (!responseOk) {
        return this.router.createUrlTree(['path', 'to', 'redirect'])
      }
      // alternatively, return a different UrlTree if you feel like it would be a good idea
      return responseOk
    })
  );
}

我还强烈建议使用他们的Guide 升级到 Angular 7。它非常轻松,它将为您提供新功能并带来大量错误修复。

【讨论】:

    【解决方案2】:

    这里是重定向到 url 的示例守卫。可能有帮助:

    export class AuthGuard implements CanActivate {    
    constructor(private router: Router, private authService: AuthenticationService) { }
    
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
        if (this.authService.isAuth) {
            return true;
        }
        else {
            this.router.navigate([state.url]); // or some other url
        }
    }}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-10
      • 1970-01-01
      • 2019-02-22
      • 2019-06-21
      • 1970-01-01
      • 2017-11-22
      • 1970-01-01
      相关资源
      最近更新 更多