簡體   English   中英

如何正確延遲加載 angular 中的組件?

[英]How to properly lazyload component in angular?

我在 Angular 中遇到了一些簡單的路由管理:我有第一個模塊:

 import { NgModule } from '@angular/core'; import { Routes } from '@angular/router'; import { RouterModule } from '@angular/router'; import { LayoutComponent } from './ui/components/layout/layout.component'; const routes: Routes = [{ path: '**', component: LayoutComponent, children: [ { path: '', redirectTo: '/posts', pathMatch: 'full'}, { path: 'posts',loadChildren: './posts/posts.module#PostsModule' }] }]; @NgModule({ imports: [RouterModule.forRoot(routes) ], exports: [RouterModule] }) export class AppRoutingModule { }

以及應該顯示簡單的“它有效”組件的“PostModule”:

 import { NgModule } from '@angular/core';\n import { Routes } from '@angular/router';\n import { RouterModule } from '@angular/router'; import { PostsComponent } from './containers/posts/posts.component'; import { ProfileComponent } from './containers/profile/profile.component'; const routes: Routes = [{ path: '', component: PostsComponent },{ path: ':profileId', component: ProfileComponent },]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class PostsRoutingModule { }

但沒有一條路線

http://localhost:4200/posts/

http://localhost:4200/posts/1

顯示預期內容

我想我錯過了一些簡單的東西,我的 app.component 看起來像這樣:

 <router-outlet> <router-outlet></router-outlet> </router-outlet>

我已經閱讀了一些關於“延遲加載”的帖子,但是我所寫的內容與我到目前為止所學的內容似乎是一致的,錯誤在哪里?

問題似乎在於您構建路由的方式。 它應該這樣配置:

const routes: Routes = [
  {
    path: '',
    component: LayoutComponent,
    children: [
      { path: 'posts', loadChildren: './posts/posts.module#PostsModule' }
    ]
  },
  { path: '**', redirectTo: '/', pathMatch: 'full' }
];

“路徑:'**'”的想法是處理您在瀏覽器中輸入的任何未定義路由(即/hello-world)並重定向到根目錄或您選擇的任何其他已定義路由。

因此,按照您定義的方式,路由始終捕獲導航並顯示 LayoutComponent。

您使用的是哪個 Angular 版本? 您是否嘗試過以下操作?

const routes: Routes = [{
  path: '**',
  component: LayoutComponent,
  children: [
    { path: '', redirectTo: '/posts', pathMatch: 'full' },
    { path: 'posts', loadChildren : () => import('./posts/posts.module').then(x => x.PostsModule) }
  ]
}];



更新:

路由器添加到路由器出口的組件被添加到外部router-outlet下方,因此在內部添加一些東西是沒有意義的。

內部的router-outlet需要移動到由路由器添加的LayoutComponent組件中。

首先嘗試執行以下操作:

   <router-outlet>
      <p>Layout Component loaded</p>
      <router-outlet></router-outlet>
   </router-outlet>

然后,如果您的登錄頁面中寫入了某些內容,請將第二個路由器插座放入您的 LayoutComponent。

為了在一個模板中並排使用多個插座,您需要使用命名的路由器插座。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM