【问题标题】:Angular 8 Default RoutingAngular 8 默认路由
【发布时间】:2020-01-15 18:52:44
【问题描述】:

我有一个运行 Angular 8.2 的应用。路由运行良好,除了默认路由。

当去website.com时,我想被重定向到website.com/sign-in

app-routing.module

const routes: Routes = [
  {
    path: '',
    redirectTo: 'sign-in',
    pathMatch: 'full'
  },
  {
    path: '',
    component: PublicLayoutComponent,
    data: { title: 'Public Views' },
    children: PUBLIC_ROUTES
  },
  {
    path: '',
    component: PrivateLayoutComponent,
    data: { title: 'Private Views' },
    children: PRIVATE_ROUTES
  },
];

public-routing.module

export const PUBLIC_ROUTES: Routes = [
  {
    path: "sign-in",
    loadChildren: () =>
      import('../features/sign-in/sign-in.module').then(
        m => m.SignInModule
      )
  }
];

private-routing.module

export const PRIVATE_ROUTES: Routes = [
  {
    path: "dashboard",
    loadChildren: () =>
      import('../features/dashboard/dashboard.module').then(
        m => m.DashboardModule
      )
  }
];

我也尝试将其添加到 app-routing.module

{
  path: '**',
  redirectTo: 'sign-in',
  pathMatch: 'full'
},

编辑:

我所有的路线都有效。当转到website.com/sign-in 时,Angular 会查看 app-routing.module,然后查看子路由以查找路由位置。如果我添加

{
  path: '**',
  redirectTo: 'sign-in',
  pathMatch: 'full'
}

public-routing.module,除空白之外的任何内容都将重定向到登录。 website.com/jdjhjdfjd 将转到我的登录页面,但 website.com 不会。

【问题讨论】:

  • 嗨。我有同样的问题..你解决了这个问题吗?

标签: angular routing components angular8


【解决方案1】:

可能是因为您尚未定义登录路径

const routes: Routes = [
  {
    path: '',
    redirectTo: 'sign-in',
    pathMatch: 'full'
  },
  ...
  {
    path: 'sign-in',
    component: SignInComponent,
    data: { title: 'Private Views' },
  },
];

【讨论】:

  • 我在子组件中定义了它。登录路由有效,我的问题是路由器默认没有路由任何东西。 website.com/sign-in 将转到登录页面,但 app-routing.module 不会重定向任何路由。即使我为两个子组件添加了一个路径,因此链接读取website.com/public/sign-in,链接仍然有效,但应用程序路由器不会从空白路由或通配符路由重定向
【解决方案2】:

因为您在应用程序路由中具有相同的 url,所以它们被最后一个覆盖。 所以你写的代码等价于(之前的被last覆盖,因为它们有相同的path


const routes: Routes = [
  {
    path: '',
    component: PrivateLayoutComponent,
    data: { title: 'Private Views' },
    children: PRIVATE_ROUTES
  }
];

在 Angular 中,您重定向的不是children,而是path 所以 必须 有一条带有 path: 'sign-in' 的路径

如果你想在这里使用延迟加载,应该有一个路径“登录”,它会在孩子中有 SignInModule 模块。在这个模块的路由中,path: '' 会有 SingnInComponent

【讨论】:

    【解决方案3】:

    你应该检查如何使用 Route Guards 或者你可以使用 Router 来重定向它:

    export class AppComponent implements OnInit { 
      constructor(private router: Router) {}
    
      ngOnInit() {
        this.router.navigate(['sign-in'])
      }
    }

    【讨论】:

      猜你喜欢
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 2021-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-18
      • 1970-01-01
      相关资源
      最近更新 更多