簡體   English   中英

Angular7:如何防止通過URL導航?

[英]Angular7: how to prevent navigation via URL?

在我的Angular應用程序中,我希望用戶只能從根URL( / )加載它。 如果用戶在瀏覽器中嘗試其他任何URL,則應立即將其重定向到根URL。

但是,應用程序中的this.router.navigate(['some-url'])重定向如this.router.navigate(['some-url'])

我怎樣才能做到這一點?

現在,我在這篇文章中看到了NavGuard ,但也許有更簡單的技巧可以做到這一點。

感謝您的想法。

您只需在app.module構造函數中添加一個router.navigateByUrl('/'),因此無論它們做什么,在應用程序加載時它們就可以到達那里。 或者,您可以在sessionStorage中創建一個包含值的變量,例如sessionStorage.setItem('userOnline', true) ,然后在OnInit中檢查該值。 由於會話存儲在選項卡關閉時被破壞,因此如果直接在瀏覽器導航欄上放置任何路由,則它們可以進行路由導航,但只有在它們已經加載了應用程序的情況下,才可以進行路由導航。 應用程序加載將重定向到“ /”。

這個想法的任何變化,都可能並且應該起作用。 請問我是否迷路了!

接受的答案是不好的做法,恕我直言

您應該嘗試以下路由模塊:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { BarComponent } from '@components/bar.component';

const routes: Routes = [
  {
    path: '**',
    redirectTo: '',
  },
  {
    path: '',
    component: BarComponent,
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class FooRoutingModule { }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM