angular - 开始路由之前的Angular 6调用后端api
问题描述
我有一个 Angular 6 应用程序。新用户需要进行快速设置才能使用该应用程序。
我正在使用后端 api 检查用户状态并查看用户是否已完成初始设置。
我正在调用这个 api,AppComponent::ngOnInit
如果LoginConponent::ngOnInit
用户正在访问/
或未经授权,这工作正常,因为在外部登录后用户将被重定向到/login
.
/profile
但是,如果用户在登录后但在完成初始设置之前手动输入 url ,用户将被重定向到/profile
页面并在后端 api 检查其状态并最终重定向到页面时看到页面一秒钟/quick-setup
。
有没有办法在应用程序启动时自动停止 Angular 路由?所以我可以手动完成吗?
我不需要也不想在每次路线更改时检查这一点,只需在应用程序启动时!
我可以以某种方式使用Resolve
它吗?
我已经必须AuthGuard
检查身份验证状态,但这将在每次路线更改时检查,这不是我想要的
解决方案
好的,这就是我为完成这项工作所做的工作。
首先进入app.component
ngOnInit(): void {
//always go to login page to authenticate and then redirect to the requested url
this.authService.navigateToLogin();
}
navigateToLogin() {
if (!Util.checkUrl('/logout') && !Util.checkUrl('/signup'))
this.router.navigate(['/login'], { skipLocationChange: true });
}
在login.component
中,将 cookie 存储location.pathname
在 cookie 中,以便登录后重定向到它
ngOnInit() {
if (!Util.checkUrl('/login') && !Util.checkUrl('/', true) && !Util.checkUrl('/#')) {
this.cookieService.set(COOKIE_LOGIN_REDIRECT, location.pathname, 3600, '/');
}
this.authService.verify();
}
this.authService.verify();
检查后端以查看用户是否正常,然后重定向到存储在 cookie 中的位置。
let redirect = this.cookieService.get(COOKIE_LOGIN_REDIRECT);
if (redirect) {
this.cookieService.delete(COOKIE_LOGIN_REDIRECT, '/');
redirect = redirect.replace(environment.baseHref, '');
return this.router.navigateByUrl(redirect);
}
推荐阅读
- performance - 在 STL 中使用 int 数组或 unordered_map 进行散列?
- sql - 强制现有行是唯一的
- hibernate - 如何在 Netbeans 中为 Hibernate 生成 DAO?
- django - Django:表单的初始值
- sql - 未受过 SQL 培训的人提出的 SQL 查询问题
- image - 混合中值滤波器如何在边缘工作?
- node.js - 未定义带有 Angular 窗口的 Dotnet 核心
- regex - 如何限制正则表达式中的可选空格匹配
- iot - LoRa:应用层为每个接收到的传输接收分段数据包?
- python - TypeError:ResultProxy 类型的对象不是 JSON 可序列化的:导致 sqlalchemy 查询?