【发布时间】:2020-07-20 18:12:44
【问题描述】:
我目前正在使用其路由器功能开发一个 Angular 应用程序。所有路由似乎都运行良好,直到我发现成功登录后,我设置的 url 路径,即“/admin”将不会被遵循,路由器默认为“/”。这是代码:
//login.component.ts
if (this.authService.getUserRole() == 'user' || 'agent') {
window.location.assign('/')
} else if (this.authService.getUserRole() == 'admin') {
window.location.assign('/admin')
}
//app.routing.ts
import {AdminComponent} from './admin-master/admin/admin.component;
import {HomeComponent} from './home/home.component;
const appRoutes: Routes = [
{path: '', component: HomeComponent, pathMatch: 'full'},
{path: 'admin', component: AdminComponent, canActivate: [AuthGuard], data: {permission:{only: ['admin']}}}
]
编辑:(添加 auth.guard.ts)
//auth.guard.ts
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
const permission = next.data["permission"];
if(this.authService.isLoggedIn() &&
permission.only.includes(this.authService.getUserRole())) {
return true;
} else {
this.router.navigateByUrl('/logout');
}
}
}
问题:
-
虽然已经成功登录,但路由器会将用户重定向到一个空白 url,而不是我在
login.component.ts文件夹中专门提供的设置 URL。 -
因为它会重定向到一个空的 URL,
home.component.html中的元素也会显示在我的管理仪表板中,这是我不希望发生的。
总之,如何正确路由以下函数?难道我做错了什么? 感谢您的帮助!
【问题讨论】:
-
您在浏览器控制台中看到了什么 (F12)
-
@Pieterjan 这就是我的路由器事件中立即显示的内容:导航开始:
NavigationStart(id: 1, url: '/') -
您的
AuthGuard是什么样的?此外,您的路由对我来说看起来有点奇怪,您没有使用路由功能中的角度构建 (angular.io/guide/router) 而不是window.location.assign('/admin'),您应该使用this.router.navigate(['admin'], { relativeTo: this.route }); -
我将编辑我的帖子以添加 AuthGuard!另外,我使用
window.location.assign的原因是为了让浏览器认为我已经重定向到该路由。这是因为我的某些功能只有在我刷新应用程序时才会加载。 -
@Pieterjan 有什么想法吗?
标签: angular typescript angular-routing