如何使用Angular 2从JSON文件获取数据

时间:2018-10-09 18:17:39

标签: angular angular2-forms

如何从json文件中获取json数据,以及如何仅使用angular 2进行显示。你能找到我在哪里弄错了

https://stackblitz.com/edit/angular2-notifications-example-fkngjs?file=app/app.component.html

this.http.request('http://localhost:4200/app/jsondata/details.json?home=place&owner=person&minval=min&maxval=max').
subscribe((res) => {
let alldetails = JSON.stringify(res); 
});

1 个答案:

答案 0 :(得分:0)

您忘记将HttpClientModule导入app.module.ts中,如下所示

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

您需要像下面这样在@NgModule中使用它-

@NgModule({
  imports: [ 
    ReactiveFormsModule,
    BrowserAnimationsModule,
    BrowserModule,
    FormsModule,
    HttpClientModule
  ],
  declarations: [ AppComponent, ExampleComponent,HeaderComponent,FooterComponent ],
  bootstrap:    [ AppComponent ]
})

这是app.module.ts的完整代码-

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

import { AppComponent } from './app.component';
import { ExampleComponent } from './example.component';
import { HttpClientModule } from '@angular/common/http';


import { FooterComponent } from './footer/footer.component';

import { HeaderComponent } from './header/header.component';



@NgModule({
  imports: [ 
    ReactiveFormsModule,
    BrowserAnimationsModule,
    BrowserModule,
    FormsModule,
    HttpClientModule
  ],
  declarations: [ AppComponent, ExampleComponent,HeaderComponent,FooterComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

但是,如果仅使用Angular 2,则需要从app.module.ts中的'@ angular / http'导入HttpModule而不是HttpClientModule。此外,您还需要使用{ {1}}来自“ @ angular / http”,而不是您的app.component.ts中的Http

这是一个有效的演示- https://stackblitz.com/edit/angular2-notifications-example-gunqm4