网站搜索

javascript - Angular 12,TypeScript 4.2:该类已列在 NgModule 的 declarations 中,但它不是指令、组件或管道


我将我的应用程序从 Angular 11 升级到了 12,同时升级到了 TypeScript 4.2.4。当我执行 ng serve 时,应用程序编译失败,出现错误:

error NG6001: The class 'ChartComponent' is listed in the declarations of the NgModule 'PrototypeModule', but is not a directive, a component, or a pipe. Either remove it from the NgModule's declarations, or add an appropriate Angular decorator.

41     , ChartComponent
         ~~~~~~~~~~~~~~~~~~~~~~~~

  src/app/chartPage/Chart/chart.component.ts:46:14
    46 export class ChartComponent implements OnInit {
                    ~~~~~~~~~~~~~~~~~~~~~~~~
    'ChartComponent' is declared here.

这是 PrototypeModule 中的代码

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

import { ChartComponent } from './chartPage/Chart/chart.component';

@NgModule({
  declarations: [
    ChartComponent
]
    schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
    
})
export class ChartPrototypeModule { }


@NgModule({
  imports: [ChartPrototypeModule]
  , exports: [],
    schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class PrototypeModule { }

ChartComponent 如下:

import {Component, Input, ViewEncapsulation, Injectable, OnInit, SimpleChange, NgModule} from '@angular/core';
import { DataLoadService } from '../../services/data-load.service';


@Component({
    selector: 'app-chart',
    templateUrl: `./chart.component.html`,
    styleUrls: ['./chart.component.scss']
    , encapsulation: ViewEncapsulation.None
})
@Injectable({
    providedIn: 'root'
})

@NgModule({
    imports: [SharedModule]
})

export class ChartComponent implements OnInit {
  constructor(private data: DataLoadService) {
        //constructor code
    };

}

我没有关于可能导致错误的线索。我该如何解决这个问题?

答案#1

所以,正如 @Muhammet Can TONBUL 提到的,你使用这个组件的方式是错误的。

首先,你的组件应该看起来像这样:

@Component({
  selector: 'app-chart',
  templateUrl: `./chart.component.html`,
  styleUrls: ['./chart.component.scss'],
  // Use this only if you DON'T want to encapsulate your SCSS
  encapsulation: ViewEncapsulation.None 
})
export class ChartComponent implements OnInit {

  constructor(private data: DataLoadService) { ... };

  ...

}

下一步是像你已经做过的那样创建一个 NgModule:

@NgModule({
  declarations: [
    ChartComponent
  ],
  schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
    
})
export class ChartPrototypeModule { }

所以,现在你已经声明了你的组件,你现在可以使用它,但目前仅能在ChartPrototypeModule的其他组件中使用。

要更改此设置,您还需要在模块中导出您的组件。这看起来大致如下:

// Introduced an additional array so it is not needed
// to add your components twice
const COMPONENTS = [
  ChartComponent
];

@NgModule({
  declarations: [
    COMPONENTS
  ],
  exports: [
    COMPONENTS
  ],
  schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
    
})
export class ChartPrototypeModule { }

现在您可以在导入了 ChartPrototypeModule 的每个模块中使用您的组件。

你可以在这里阅读更多关于功能模块的内容。

注意: 如果您使用引入的数组 COMPONENTS 来减少冗余,只需将那些您希望在模块外使用的组件添加到其中。

答案#2

如果这能帮到大家:我遇到了完全相同的问题,并且从语法上看一切似乎都是正确的(在组件和模块中)。然后我意识到 import { Component } from '@angular/core'; 缺失了!出于某种原因,VSCode 没有提示这个问题,而且该导入被随机移除了。现在构建运行得非常顺利。