首页 > 解决方案 > 无法根据订阅的数据使用 authgaurd

问题描述

if (localStorage.getItem('localcache') && this.authservice.getAdmin().subscribe(data => {

    return data['status'];
  }, error => {

    return false;
  })) {

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

我正在尝试根据服务器响应设置 authgaurd 返回值,但是如果服务器发生错误意味着 403 等 authgaurd 不起作用,请举个例子

标签: angular

解决方案


您需要返回一个Observable以便 auth 守卫等待您的getAdmin呼叫,您也可以UrlTree直接返回一个让守卫重定向到登录路由:

return this.authservice.getAdmin().pipe(
  map(({ status })=> !!localStorage.getItem('localcache') && status),
  catchError(() => of(false)),
  map(isAdmin => isAdmin || this.router.parseUrl('/login');),
);

推荐阅读