0

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

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

4

2 回答 2

0

这里是重定向到 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
    }
}}
于 2018-11-28T06:37:42.200 回答
0

我知道这个问题具体说明了 Angular 6,我只想提一下,从 Angular 7.1 开始,您可以返回一个 UrlTree,或者从您的警卫那里返回一个布尔值 - 以及Promise等价Observable物 - ,这将作为自动重定向。所以在你的情况下:

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 。它非常轻松,它将为您提供新功能并带来大量错误修复。

于 2018-11-28T02:00:32.997 回答