在 Angular 中,可以通过 app.module.ts 文件中的 APP_BASE_HREF 常量来设置应用程序的基础 URL。以下是一个示例:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [
{ provide: 'APP_BASE_HREF', useValue: '/my-app' } // 设置应用程序的基础 URL
],
bootstrap: [AppComponent]
})
export class AppModule { }
在上面的示例中,应用程序的基础 URL 被设置为 /my-app。在组件中使用 RouterModule 时,可以通过 basePath 选项来指定路由的基础路径,示例如下:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component';
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' }
];
@NgModule({
imports: [RouterModule.forRoot(routes, { basePath: '/my-app' })], // 设置路由的基础路径
exports: [RouterModule]
})
export class AppRoutingModule { }
在上面的示例中,路由的基础路径被设置为 /my-app。这样,访问 /my-app/home 就会显示 HomeComponent,访问 /my-app/about 就会显示 AboutComponent。