我有一个有角度的应用程序,它由几个不同的子模块组成,我将其描述为“迷你应用程序”,它们大多保持独立。在“迷你应用程序”模块中,我希望它们定义自己的路由打字稿文件(这样我可以利用 url 路径),但也能够导航到其他“迷你应用程序”模块(只是到它们的默认登陆)页数差不多)。然而,一个关键的事情是我不想在我的 app.module 中导入这些模块,因为这违背了让它们成为只能延迟加载必要的模块和组件的模块的目的,但是如果我我误解了这一点。
默认情况下,我从主应用程序模块转到主模块,如下所示:
//app-routing.module.ts (parent routing file)
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' }, // Redirect to Home module
{ path: 'home', loadChildren: () => import('./modules/home/home.module').then(m => m.HomeModule) },
{ path: 'dealer', loadChildren: () => import('./modules/dealer/dealer.module').then(m => m.DealerModule) }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
然后在我的“home”模块中定义我的路线和默认路径:
//home-routing.module.ts (child routing file)
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './components/home/home.component';
import { MarketplaceComponent } from './components/marketplace/marketplace.component';
import { WelcomeComponent } from './components/welcome/welcome.component';
const routes: Routes = [
{
path: '',
component: HomeComponent,
children: [
{ path: 'welcome', component: WelcomeComponent },
{ path: 'marketplace', component: MarketplaceComponent },
]
},
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class HomeRoutingModule { }
在默认的 HomeComponent 内部,我有
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrl: './home.component.scss'
})
export class HomeComponent {
constructor(private router: Router) { }
ngOnInit(): void {
this.router.navigate(['welcome']);
}
}
不知何故,这有点工作,但从该页面导航是不可能的(除非导航到外部模块),但现在它甚至无法从主页进入欢迎页面,并且 URL 仍为“localhost:4200”。我在浏览器控制台中收到几个如下所示的警告:
Module "url" has been externalized for browser compatibility. Cannot access "url.parse" in client code.
有办法实现我想要做的事情吗?我想是这样,因为模块可以拥有自己的路由和子级,但如果不将其导入模块以使用应用程序路由,我就无法弄清楚它。
您可以像这样配置路由来执行重定向。
//home-routing.module.ts (child routing file)
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './components/home/home.component';
import { MarketplaceComponent } from './components/marketplace/marketplace.component';
import { WelcomeComponent } from './components/welcome/welcome.component';
const routes: Routes = [
{
path: '',
component: HomeComponent,
children: [
{ path: 'welcome', component: WelcomeComponent },
{ path: 'marketplace', component: MarketplaceComponent },
{ path: '', redirectTo: 'welcome' , pathMatch: 'full' }
]
},
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class HomeRoutingModule { }
我们可以从 home 组件中删除
navigate
,因为我们已经通过 home 子路由配置了导航