【问题标题】:Angular2: Route redirect with AuthGuardAngular2:使用 AuthGuard 进行路由重定向
【发布时间】:2017-06-09 04:14:34
【问题描述】:

如果用户未登录,我有一个 Angular2 应用程序应该阻止到某个页面的路由。这是我的 app.routes 文件

export const routes: Routes = [
  { path: '', component: LoginComponent },
  { path: 'login', component: LoginComponent },
  { path: 'home', component: HomeComponent, canActivate: [AuthGuard] },
  { path: '**', component: LoginComponent },
];

还有我的 AuthGuard 文件

@Injectable()
export class AuthGuard implements CanActivate {
response: ResponseInterface;

constructor(private router: Router, private localStorage: LocalStorageService,
 private services: MyService) { }
canActivate() {

let token = String(this.localStorage.get('token'));
if (token != null) {
  this.services.keepAlive(token).subscribe(
    response => this.response = response,
    error => alert(error),
    () => {
      if (this.response.status == 'OK') {
        console.log("response OK");
        return true;
      } else {
        console.log("response KO");
        this.router.navigate(['/login']);
        return false;
      }
    }
  )

} else {
  this.router.navigate(['/login']);
  return false;
}

现在,如果我尝试导航到 http://localhost:4200/#/home 路径并且我已经将令牌存储到 localStorage 中,则什么也不会发生:主页未显示并且导航栏上的路径变为 http://localhost:4200/#/。 怎么了?

【问题讨论】:

  • 那么你在日志中看到“响应OK”了吗?
  • 是的,响应正常
  • 不,我的意思是你的代码中有一个console.log("response OK");。你在控制台日志中看到了吗?
  • 我收到两个响应都OK,并且“响应OK”显示在日志中,因此到达了那部分代码

标签: angular routing angular-routing


【解决方案1】:

canActive 方法应返回 Observable<boolean>Promise<boolean>boolean

您订阅了this.services.keepAlive Observable,并将boolean 值返回给订阅回调,而不是返回给canActivate 方法。更改您的代码如下:

canActivate(): Observable<boolean> | Promise<boolean> | boolean {
    let token = String(this.localStorage.get('token'));
    if (token != null) {
        return this.services.keepAlive(token)
            .map(response => {
                if (response.status == 'OK') {
                    console.log("response OK");
                    return true;
                } else {
                    console.log("response KO");
                    this.router.navigate(['login']);
                    return false;
                }
            });
    } else {
        this.router.navigate(['login']);
        return false;
    }
}

这样,布尔类型 (Observable&lt;boolean&gt;) 的 Observable 将返回到 canActive 方法,并且路由解析应该按预期工作。

【讨论】:

  • 它是订阅 observable 并将布尔值返回给订阅回调,而不是返回给 canActive 方法。
  • 我在 canActivate() 签名上收到此错误:“返回表达式中不存在最佳通用类型。”
  • 定义canActive方法的返回类型如下: canActivate(): Observable |承诺 |布尔 { ... }。我也会更新答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-19
  • 1970-01-01
  • 2017-06-25
  • 1970-01-01
  • 2013-03-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多