如何正确地懒惰角组件?

我对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>

我已经读过一些有关“延迟加载”的帖子,但是我写的内容与到目前为止所学的内容似乎是一致的,错误在哪里?

xyx006 回答:如何正确地懒惰角组件?

问题似乎出在您构造路由的方式上。应该这样配置:

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: '**',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中。

为了在一个模板中并排使用多个插座,您需要使用命名路由器插座。

本文链接:https://www.f2er.com/3100831.html

大家都在问