有没有办法在 Angular 中延迟加载组件而不是模块? [英] Is there a way to lazy load components, not modules, in Angular?

查看:27
本文介绍了有没有办法在 Angular 中延迟加载组件而不是模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

延迟加载是一种常用的技术.然而,在 Angular 中,这种技术的粒度级别似乎停留在模块级别.

Lazy loading is a commonly used technique. However, in Angular it seems that the granularity level of this technique stops at the module level.

这意味着您可以在浏览器中加载 main 模块,然后在特殊情况下可以延迟加载模块 B、C 和 D.

That means that you can have module main that loads in the browser, and then on special occasion module B and C and D can be loaded lazily.

几乎所有网络教程都解释了这一点.但是,有没有办法懒加载组件?

Almost all tutorials on web explain that. However, is there a way to load components lazily?

考虑这个简单的例子,用户进入应用程序,当点击发票"链接时,URL 更改为新路由 /invoice/list 并且进度条显示正在加载,而 invoices 组件包括 HTML 和 JS 正在浏览器中加载,在主模块中动态注册,并显示在相关的插座中.Angular 可以做到这一点吗?

Consider this simple example that user goes inside the application, and when clicks "invoices" link, URL changes to the new route /invoice/list and a progress bar shows loading, while the invoices component including HTML and JS is being loaded inside the browser, is registered dynamically with the main module, and is being shown in the relevant outlet. Is that possible with Angular?

推荐答案

延迟加载组件是不可能的.这种行为的原因是 angular 的结构.angular 组件必须是模块的一部分.Angular 模块是一个容器,您可以在其中定义所有组件、服务、管道等.目前在里面.在构建应用程序 dist 时,模块中声明的所有依赖项都包含在一个块中(转译的 js 代码).所有直接导入的模块一起形成主块,而标记为延迟加载的模块形成一个单独的块,该块位于服务器上,直到命中相应的路由并从客户端对其进行调用.现在组件不形成块,因此不可能

Lazy loading a component is not possible. Reason for this behavior is the structure of angular. Components in angular have to be part of a module. Angular module is a container where you define all the components, services, pipes e.t.c. present inside. While building the application dist, all the dependencies declared in the module are included to make a chunk (transpiled js code). All the directly imported modules together form the main chunk whereas modules marked as lazily loaded form a separate chunk that sits on the server untill the respective route is hit and a call for it is made from the client. Now components do not form a chunk and hence it is not possible

这篇关于有没有办法在 Angular 中延迟加载组件而不是模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆