【问题标题】:How to route the angular url to default component?如何将角度 url 路由到默认组件?
【发布时间】:2021-08-08 02:55:14
【问题描述】:

我正在通过修改英雄联盟代码来练习。

我在路由中,如果除了 localhost:4200 之外什么都不传递,那么它会重定向到仪表板组件。

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { DashboardComponent } from './dashboard/dashboard.component';
import { HeroesComponent} from './heroes/heroes.component'

const routes: Routes = [{path: 'heroes', component: HeroesComponent},
                        {path: 'dashboard', component: DashboardComponent } ,
                        {path: '', redirectTo: '/dashboard', pathMatch:'full' },
                        ];

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

但是如果我删除这一行,就会发生一些奇怪的事情

 {path: 'dashboard', component: DashboardComponent }

然后它停止重定向到仪表板组件。为什么?它不应该影响到仪表板的路由,因为它就在 path:'' 代码的上方,而且我没有在 url 中传递 /dashboard。为什么会影响默认路径代码?

【问题讨论】:

    标签: angular typescript angular8 angular-routing


    【解决方案1】:

    要定义根路径,一个空路径就足够了。只需将其重定向到 DashboardComponent。您不必使用 redirect To 将其重定向。

    import { NgModule } from '@angular/core';
    import { Routes, RouterModule } from '@angular/router';
    import { DashboardComponent } from './dashboard/dashboard.component';
    import { HeroesComponent} from './heroes/heroes.component'
    
    const routes: Routes = [{path: 'heroes', component: HeroesComponent},
                            {path: '', component: DashboardComponent }
                            ];
    
    @NgModule({
      imports: [RouterModule.forRoot(routes)],
      exports: [RouterModule]
    })
    export class AppRoutingModule { }
    

    【讨论】:

    • 是的,我知道,但是我的代码背后的原因是什么?
    【解决方案2】:

    影响它,因为您的路径使用属性 "redirectTo" 并且引用 现有路径,在本例中为 "/dashboard" 因此,如果该路径不存在(如果您删除路径“/dashboard”),则重定向将失败。

    如果您想在不参考其他路径的情况下进行重定向,您可以使用 Sander Wooming 的建议

    【讨论】:

      猜你喜欢
      • 2018-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-09
      • 1970-01-01
      • 2018-04-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多