Angular:HttpClientModule 导入错误(无法解析为 NgModule 类)

32 typescript angular

我试图在假 json 服务器上构建一个带有 crud 的简单应用程序

但我无法导入HttpClientModule

这是来自VS Code 的错误消息:

ERROR in node_modules/@angular/common/http/http.d.ts:2801:22 - error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class.

    This likely means that the library (@angular/common/http) which declares HttpClientModule has not been processed correctly by ngcc, or is not compatible with Angular Ivy. Check if a newer version of the library is available, and update if so. Also consider checking with the library's authors to see if the library is expected to be compatible with Ivy.

    2801 export declare class HttpClientModule {
Run Code Online (Sandbox Code Playgroud)

这是app.module.ts

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { EmployeeCreateComponent } from './employee-create/employee-create.component';
import { EmployeeEditComponent } from './employee-edit/employee-edit.component';
import { EmployeeListComponent } from './employee-list/employee-list.component';

import { HttpClientModule } from '@angular/common/http';


@NgModule({
  declarations: [
    AppComponent,
    EmployeeCreateComponent,
    EmployeeEditComponent,
    EmployeeListComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'restTest6';
}
Run Code Online (Sandbox Code Playgroud)

请注意:我没有在其他任何地方使用HttpClientModule。我导入并执行并ng serve -o出现错误。请指出哪里出了问题

Dav*_*vid 61

我遇到了同样的问题,我只是运行以下命令,然后它就可以正常工作了,没有任何错误。

npm cache verify
Run Code Online (Sandbox Code Playgroud)

如果没有,请尝试手动删除node_modules文件夹并使用npm install.

rm -rf node_modules
npm install
Run Code Online (Sandbox Code Playgroud)

在 npm > 6 上,您还可以运行npm ci,这也会删除node_modules文件夹并在之后重新安装软件包。

编辑正如其他答案所建议的,ng serve如果上述步骤不起作用,您可能需要重新启动(但它们通常会起作用)


小智 37

在添加新包之前停止 ng serve,添加新包后重新启动 ng serve。这将解决这个问题。


小智 6

首先停止 ng 服务并运行这些命令...

npm cache verify
rm -rf node_modules
npm install
Run Code Online (Sandbox Code Playgroud)

安装后使用命令构建并运行您的项目

ng build
ng serve
Run Code Online (Sandbox Code Playgroud)

它对我有用并解决问题......