【问题标题】:If '<x>' is an Angular component, then verify that it is part of this module如果 '<x>' 是一个 Angular 组件,则验证它是该模块的一部分
【发布时间】:2018-07-07 10:57:06
【问题描述】:

我在使用 Angular 的组件时遇到问题。我的应用程序只使用一个模块(app.module)。我创建了一个名为“BooksComponent”的组件,其中包含用于 html 的选择器“app-books”。当我在 app.component 中使用它时,出现此错误:

'app-books' 不是已知元素: 1. 如果“app-books”是一个 Angular 组件,那么验证它是这个模块的一部分。 2. 如果“app-books”是一个 Web 组件,则将“CUSTOM_ELEMENTS_SCHEMA”添加到该组件的“@NgModule.schemas”以禁止显示此消息。

我的代码是这样的:

books.component.ts

import { Component, OnInit } from '@angular/core';
import { Book } from '../book';
import { BOOKS } from '../mock-books';


@Component({
  selector: 'app-books',
  templateUrl: './books.component.html',
  styleUrls: ['./books.component.css']
})
export class BooksComponent implements OnInit {

        books = BOOKS;
        selectedBook : Book;

  constructor() { }

  ngOnInit() {
  }

}

app.component.ts

import { Component } from '@angular/core';


@Component({
  selector: 'app-root',
  template: `<h1>{{title}}</h1>
            <app-books></app-books>`
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'BookShelf';
}

最后: app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';


import { AppComponent } from './app.component';
import { BooksComponent } from './books/books.component';
import { BookDetailComponent } from './book-detail/book-detail.component';


@NgModule({
  declarations: [
    AppComponent,
    BooksComponent,
    BookDetailComponent,

  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

我已经在 app 模块中声明并导入 BooksComponent,所以我无法理解我缺少什么!请帮忙!

【问题讨论】:

  • 您是否使用“ng g c books”创建了组件?我认为您的代码显然没有错误。
  • 一件事 - 你在&lt;app-books&gt;&lt;/app-books&gt; 后面漏掉了一个逗号,但想知道这是否会导致你的错误
  • 是的,我用 ng genetate 创建了组件.. @J.D.你是对的,我添加了逗号,但我仍然得到同样的错误......

标签: angular typescript


【解决方案1】:

如果您在运行测试时遇到错误,这可能意味着规范需要了解新组件 BooksComponent

为了解决此问题,请将以下内容添加到您的 app.component.spec.ts 文件中。

import { BooksComponent } from './books/books.component';

并在 beforeEach() 方法的声明中,添加新组件,如下所示:

beforeEach(async(() => {
  TestBed.configureTestingModule({
    declarations: [
      AppComponent, BooksComponent
    ],
  }).compileComponents();
}));

【讨论】:

  • 这里的TestBed 是什么? beforeEach 哪里来的?
  • @YanYang, TestBed -“为单元测试配置和初始化环境,并提供在单元测试中创建组件和服务的方法。” angular.io/api/core/testing/TestBed
【解决方案2】:

对我来说,问题似乎是 John Papa 的 Angular 8 的 VSCode 扩展 Angular sn-ps。(也就是说,如果您在应用程序模块中声明了组件并且错误仍然存​​在)。禁用扩展程序让我的问题消失了

【讨论】:

    猜你喜欢
    • 2021-01-23
    • 2021-12-02
    • 2017-10-11
    • 1970-01-01
    • 2021-04-20
    • 2023-03-03
    • 1970-01-01
    • 2018-07-08
    • 2021-11-11
    相关资源
    最近更新 更多