Angular 模块封装概念常见的错误理解
2023-09-14 09:03:59 时间
Angular 以类似于 ES 模块的方式引入了模块封装的概念。 它基本上意味着可声明的类型——组件、指令和管道——只能由在该模块内声明的组件使用。 例如,如果我尝试使用下面的代码在 App 模块的 App
组件内使用 A
模块中的 a-comp
:
@Component({
selector: 'my-app',
template: `
<h1>Hello {{name}}</h1>
<a-comp></a-comp>
`
})
export class AppComponent { }
会收到这个错误消息:
Template parse errors: ‘a-comp’ is not a known element
这是因为 App 模块中没有声明 a-comp。 如果我想使用这个组件,我需要导入定义这个组件的模块。解决方案如下:
@NgModule({
imports: [..., AModule]
})
export class AppModule { }
这就是封装发挥作用的地方:A 模块必须通过将 a-comp 添加到 exports 数组来将其声明为在其他 module 内可用:
@NgModule({
...
declarations: [AComponent],
exports: [AComponent]
})
export class AModule { }
大多数 Angular 新手认为 Providers 也有封装,这种想法是错误的。可以在应用程序内的任何位置访问在任何非延迟加载模块中声明的 Providers.
Modules hierarchy
关于 imported modules
的最大困惑是开发人员认为这些被导入的 Modules 在应用运行时维护了一种层次结构,并且假设导入其他模块的模块成为被导入模块的父模块。
然而,事实并非如此。所有模块在编译阶段合并
。因此,导入的模块和导入的模块之间没有层次关系。
所需命名空间之一被定义为默认命名空间。 此命名空间的控制标记不需要前缀。
<View>
标签是必需的,在上面的示例中,核心命名空间在第一行定义。 当然开发人员可以定义任何名称。 例如,为了使标签名称更短,还可以使用 c
而不是 core
.
相关文章
- [Angular] Data Resolver
- [Angular] Angular Advanced Features - ng-template , ng-container, ngTemplateOutlet
- [Angular2 Form] Use RxJS Streams with Angular 2 Forms
- [AngularJS] Using the LocalForage library for offline storage with Angular
- [Angular] Architectures for Huge Angular Based Enterprise
- [Angular 2] Import custom module
- [AngularJS] Angular 1.3 ngMessages with ngAnimate
- [Angular] In angular world and out angular world
- NgRx 和 Angular CLI 版本不一致的错误
- Angular 依赖注入错误消息:ERROR Error NullInjectorError No provider for XX
- 关于 Angular 应用的入口
- Angular:why click add button does not work for the second time
- Angular 服务器端渲染的一个错误消息 - No provider for InjectionToken REQUEST
- Angular 内容投影出现 No provider for TemplateRef found 错误的单步调试
- 为 Angular service 注册 provider 的三种方式
- Angular 依赖注入里factory函数的调用时机
- 如何在Angular单元测试里,对class protected方法进行测试
- Angular单元测试遇到的错误消息:Uncaught Error - Cannot find module tslib
- Angular ERROR NullInjectorError: R3InjectorError(AppModule)的错误分析
- Angular async pipe在Component html模板中的一个实际应用
- Angular单元测试的一个错误消息
- 如何处理Angular应用的错误消息: No pipe found with name async
- 使用Stackblitz一分钟之内创建一个Angular应用
- Angular:都2021年了,你为啥还没用Angular