【问题标题】:How do I avoid a "Unexpected module 'HttpClientModule' ... annotation" error?如何避免“意外模块'HttpClientModule'...注释”错误?
【发布时间】:2019-12-22 00:11:52
【问题描述】:

我正在使用 Angular 7 并尝试从 Rails 5 应用程序读取 JSON 数据。我的 src/app/app.component.ts 文件中有以下内容...

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

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

  constructor(private http: HttpClient) {
    http.get('http://localhost:3000/books.json')
      .subscribe(res => this.books = res);
  }
}

这在我的 ./src/app/app.module.ts 文件中

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


import { AppComponent } from './app.component';


@NgModule({
  declarations: [
    HttpClientModule,
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

但是,当我在http://localhost:4200 访问我的网页时,我收到了这个错误

compiler.js:486 Uncaught Error: Unexpected module 'HttpClientModule' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation.
    at syntaxError (compiler.js:486)
    at eval (compiler.js:15296)
    at Array.forEach (<anonymous>)
    at CompileMetadataResolver.getNgModuleMetadata (compiler.js:15278)
    at JitCompiler._loadModules (compiler.js:34413)
    at JitCompiler._compileModuleAndComponents (compiler.js:34374)
    at JitCompiler.compileModuleAsync (compiler.js:34268)
    at CompilerImpl.compileModuleAsync (platform-browser-dynamic.js:239)
    at PlatformRef.bootstrapModule (core.js:5578)
    at eval (main.ts:11)

我错过了什么?

【问题讨论】:

标签: angular http dependency-injection module


【解决方案1】:

您需要在 imports 下而不是 declarations

下拥有 HttpClientModule
@NgModule({
  declarations: [    
    AppComponent
  ],
  imports: [
    HttpClientModule,
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

【讨论】:

    猜你喜欢
    • 2017-05-16
    • 1970-01-01
    • 2019-09-28
    • 2013-06-22
    • 1970-01-01
    • 2021-10-07
    • 2020-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多