我正在Angular 10.1.6中尝试路由和延迟加载,由于某种原因,我无法发现,模块的路由和延迟加载似乎根本不起作用。我曾尝试将其与Angular网站上的stock example代码进行比较,但即使经过多次尝试来解决该问题,我仍然找不到问题。
我的App.module:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { EventsComponent } from './events/events.component';
@NgModule({
declarations: [AppComponent, EventsComponent],
imports: [BrowserModule, AppRoutingModule],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
这是我的应用程序路由模块:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { EventsComponent } from './events/events.component';
const routes: Routes = [
{ path: 'events', component: EventsComponent },
{
path: 'user',
loadChildren: () =>
import('./User/user-profile/user-profile.module').then(
(m) => m.UserProfileModule
),
},
{ path: '**', redirectTo: '', pathMatch: 'full' },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}
app.component模板仅具有2个按钮,可根据需要将路由器链接设置为URL。 app.component.html看起来像这样:
<p>{{ title }}</p>
<button [routerLink]="['events']">Events</button>
<button [routerLink]="['user/profile']">User Profile</button>
我要延迟加载的模块,用户配置文件模块如下所示:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { UserProfileRoutingModule } from './user-profile-routing.module';
import { UserProfileComponent } from './user-profile.component';
@NgModule({
declarations: [UserProfileComponent],
imports: [CommonModule, UserProfileRoutingModule],
})
export class UserProfileModule {}
并具有自己的路由模块,例如:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { UserProfileComponent } from './user-profile.component';
const routes: Routes = [{ path: 'profile', component: UserProfileComponent }];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class UserProfileRoutingModule {}
我在做什么错/错了,路由和延迟负载不能简单地工作?
单击按钮的结果就是这样:
完整的项目代码在这里:https://bitbucket.org/Anirudh_Nandavar/lazyload_angular/src/master/
预先感谢您的帮助!
答案 0 :(得分:1)
您忘记在您的<router-outlet>
中放置app.component.html
标记:
<p>{{ title }}</p>
<button [routerLink]="['events']">Events</button>
<button [routerLink]="['user/profile']">User Profile</button>
<router-outlet></router-outlet> <================================= this one