angular - 无法根据订阅的数据使用 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 不起作用,请举个例子
解决方案
您需要返回一个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');),
);
推荐阅读
- javascript - Javascript无法将日期格式化为工作日后跟天
- javascript - 将现有列表中的标签动态添加到 Select2
- docker - 如何将 docker-compose 连接到容器网络和 localhost 网络
- excel - 查找一个值,然后使用下拉列表中的“是”或“否”修改右侧的单元格 4 列
- node.js - 从 node.js 发送电子邮件到 Gmail
- cdi - 动态 CDI 注入 @Named
- android - Flutter 将 Image 转换为 base64 和 base64 String 转换为 Image
- java - 为什么我们需要在 Guice 模块中实现 configure()?
- python - 如果在 Jquery Autocomplete 和 Django 中不是唯一的,如何仅显示一个结果
- javascript - Vanilla JS equivalent of jQuery's slice method