📜  设置默认路由角度 - TypeScript (1)

📅  最后修改于: 2023-12-03 15:28:08.523000             🧑  作者: Mango

设置默认路由角度

在 Angular 应用程序中设置默认路由可能会非常有用。这可以确保应用程序在加载时引导到指定的组件。在 TypeScript 中,以下是如何设置默认路由的示例:

在 app-routing.module.ts 文件中,将默认路由设置为组件的路径。例如,如果我们想要将默认路由设置为 HomeComponent 组件,我们可以这样写代码:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';

const routes: Routes = [
  { path: '', component: HomeComponent },
  // other routes...
];

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

注意到在路由定义中,path 为空字符串。这意味着当路由匹配为空时,将路由到 HomeComponent 组件。

当然,我们可以根据需要更改默认路由。例如,如果我们想要将默认路由设为 LoginComponent 组件,我们可以将代码更改如下:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from './login/login.component';

const routes: Routes = [
  { path: '', component: LoginComponent },
  // other routes...
];

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

这样,当路由匹配为空时,将路由到 LoginComponent 组件。

以上就是在 TypeScript 中设置默认路由的方法。这可以确保我们的应用程序在加载时路由到指定的组件。