简体   繁体   English

Angular 延迟加载模块重新加载应用程序

[英]Angular lazy loading module reloads application

I lazy load a module.我懒加载一个模块。 When changing the route which points to it, the whole app reloads and app.component ngOnInit() function is called again (which is undesirable since I subscribe to the server and need to do this only once).当更改指向它的路由时,整个应用程序会重新加载并再次调用 app.component ngOnInit() 函数(这是不可取的,因为我订阅了服务器并且只需要执行一次)。 I found out that loading the module without refreshing the whole app is called 'Hot module reload' (HMR) and there are some packages that should help with that, however I would expect this to be handled by Angular itself.我发现在不刷新整个应用程序的情况下加载模块称为“热模块重新加载”(HMR),并且有一些包应该对此有所帮助,但是我希望这由 Angular 本身处理。 This issue happens only with lazy loaded modules.这个问题只发生在延迟加载的模块上。

app.component.html应用程序组件.html

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

app.component.ts app.component.ts

ngOnInit(): void {
  console.log('App init');
  this.realtimeService.subscripbeToRT(); // Should be called only once
}

app.module.ts app.module.ts

const routes: Routes = [
    { path: '', component: HomeComponent },
    {
        path: 'test',
        loadChildren: () => import('./test/test.module').then(m => m.TestModule)
    },
    { path: '**', redirectTo: '' }
];

@NgModule({
      declarations: [
         ...
      ],
      imports: [
         RouterModule.forRoot(routes),
         ...
      ],
      bootstrap: [AppComponent]
  })

  export class AppModule { }

In the example above, the real-time service is called on the route change to /test page.在上面的例子中,实时服务在路由改变到 /test 页面时被调用。 Does anyone know how to disable the whole app refresh when loading the lazy module?有谁知道如何在加载惰性模块时禁用整个应用程序刷新?

Thank you谢谢

can you share a plunker/stackblitz where you're doing this.你能分享一个你正在做这个的plunker/stackblitz吗? the scenario described by you is unusual.你描述的场景不寻常。

HMR is required in development mode .开发模式需要 HMR it's not used in production.它不在生产中使用。

In the end the issue was using href on some anchor tags instead of routerLinks.最后,问题是在某些锚标记上使用 href 而不是 routerLinks。 Now the app behaves as exprected.现在该应用程序的行为符合预期。

我有同样的问题,因为我在我的顶栏中而不是使用 click=goto(/blah) 而在 ts 文件中做 this.router.navigate(url) 解决了这个问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM