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

查看:359
本文介绍了有没有办法在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,进度条显示正在加载,而正在包含HTML和JS的invoices组件加载到浏览器中,并在主模块中动态注册,并显示在相关的插座中. 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模块是一个容器,您可以在其中定义所有组件,服务和管道等.在里面. 在构建应用程序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天全站免登陆