• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Angular 使用modulecomponent的坑

武飞扬头像
艾萨克SU
帮助1

在一个module中使用另一个module的componet

最近在使用Angular做一个项目,之前对于angular的接触不多,所以使用过程中碰到了一些坑,在此记录其中一个

error

先上报错信息:

Error: src/app/product/product-list/product-list.component.html:2:1 - error NG8001: 'app-star' is not a known element:
1. If 'app-star' is an Angular component, then verify that it is part of this module.
2. If 'app-star' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

下面详细解释错误的产生和解决方案

需求

一个很简单的需求,希望在product-list component (属于product module)中使用shared module中的star component. 工程目录app下的结构如下:

app
│  app-routing.module.ts
│  app.component.css
│  app.component.html
│  app.component.spec.ts
│  app.component.ts
│  app.module.ts
│
├─products
│      product-list.component.css
│      product-list.component.html
│      product-list.component.spec.ts
│      product-list.component.ts
│      products.module.ts
│
└─shared
        shared.module.ts
        star.component.css
        star.component.html
        star.component.spec.ts
        star.component.ts
学新通

创建过程

创建工程的步骤如下:

ng n mouduletest  //接下来的Add routing选Y,stylesheet 选CSS
ng g m products
ng g c products/product-list --flat
ng g m shared
ng g c shared/star --flat

在app-routing-module中增加路径定义并增加import:

import { ProductListComponent } from './product/product-list/product-list.component';
const routes: Routes = [
  {path:'',component:ProductListComponent}
];

这时候如果ng serve 是没有问题的,能够显示product-list works!

引入star component

在shared module 中export star component .
将shared.module中@NgModule声明中增加:

  exports:[
    StarComponent
  ]

然后在product-list module中import star module
在product.module的@NgModule声明中imports中增加SharedModule:

  imports: [
    CommonModule,
    SharedModule
  ],

再在product-list.componet.html中增加对star的引用。
增加:

<app-star></app-star>

这时候ng serve,报错了,错误内容就是开头的内容。

查找问题

经过了多方搜索,搜到结果最多的就是要在shared.module中增加exports,可是这个我已经做了。

转机

后来看了一个课程里面讲module,里面用到的结构跟我用到的差不多,但是是可以工作的,按照里面的命令和操作抄了一遍,居然能工作。

查找问题

下面的工作就变成了查看这两个工程的差异了,我按照无限接近的方式生成了一系列的工程,按照创建过程中的步骤把工程做的无限接近成功的工程。发现还是报错。
然后拿出beyond compare比较两个文件夹中的内容。最终发现了端倪。
成功的工程中app.module中@NgModule的imports中多了一行ProductModule.

然后我在之前error的工程中都照此加上,成功了。

总结一下

我感觉非常诡异的一点,app.module中没有import ProductModule,如果ProductModule中不引用其他module,那么能够正常使用,可是如果ProductModule中引用了SharedModule,那么就必须在appModule中引用 ProductModule,让我感到非常诡异,没有理解其中的逻辑,但是不管怎样,终于找到了问题。

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgggjcj
系列文章
更多 icon
同类精品
更多 icon
继续加载