Angular 如何让某些页面不能直接通过 URL 请求?
目前访问 http://localhost:4200
会重定向到 /home, 进入到后台管理系统布局首页
菜单用的是 [routerLink]
属性指定路由
<a
*ngSwitchCase="MenuType.SIDENAV_INSIDE"
[routerLink]="menu.link" matRipple [matRippleColor]="rippleColor"
[ngClass]="{'active':menu.link === router.routerState.snapshot.url}">
<mat-icon class="ms-3">{{ menu.icon }}</mat-icon>
<span>{{ menu.name | translate }}</span>
</a>
需求
- 如果点击菜单来请求页面, 则正常访问
- 只有
http://localhost:4200
和http://localhost:4200/home
可以直接通过 URL 请求, 其他路由如果直接通过 URL 请求, 则重定向到一个 Error 页面在 Angular 中如何判断路由是否直接通过 URL 请求过来的?
回复
1个回答

test
2024-07-12
也许可以尝试以下两种方案,两个方案都可以放在根组件中。
第一种:
constructor(private router: Router){
}
ngOnInit() {
// 可以先试试这个,看打印什么
console.log(this.router.url);
// 如果上面的不行,就尝试用这个
this.router.events.filter(event => event instanceof NavigationEnd)
.pipe(first()) // 只获取首个
.subscribe(event =>
{
// 盘的这个event.url,然后实现你的逻辑
console.log(event.url);
});
}
}
第二种:
constructor(private location: Location){}
ngOnInit() {
// 再试试这个
console.log(this.location.path());
}
如果上面两个具体的写法都不行,那么就在浏览器中断一下,看看还有什么属性,这些属性里应该有你想要的,希望能帮到你。
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容