Angular 如何让某些页面不能直接通过 URL 请求?

目前访问 http://localhost:4200 会重定向到 /home, 进入到后台管理系统布局首页

image.png

菜单用的是 [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>

需求

  1. 如果点击菜单来请求页面, 则正常访问
  2. 只有 http://localhost:4200http://localhost:4200/home 可以直接通过 URL 请求, 其他路由如果直接通过 URL 请求, 则重定向到一个 Error 页面
    在 Angular 中如何判断路由是否直接通过 URL 请求过来的?
回复
阅读 407
1 个回答

也许可以尝试以下两种方案,两个方案都可以放在根组件中。

第一种:

 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());
 }

如果上面两个具体的写法都不行,那么就在浏览器中断一下,看看还有什么属性,这些属性里应该有你想要的,希望能帮到你。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏