我正在使用 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)
我错过了什么?
你需要HttpClientModule
下imports
不下declarations
@NgModule({
declarations: [
AppComponent
],
imports: [
HttpClientModule,
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句