【问题标题】:How to get data from json file using angular 2如何使用 Angular 2 从 json 文件中获取数据
【发布时间】:2018-10-10 02:33:30
【问题描述】:

如何从 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); 
});

【问题讨论】:

  • 在 stackblitz 上使用 localhost:4200 不起作用
  • 该文件在本地可用吗?查询字符串是做什么用的?有没有可以在线获取这些数据的地方?
  • @gayathrin 检查我的答案,你错过了导入
  • @gayathri,你的 .json 文件必须在 assests 文件夹中,并提出关于 this.http.get('assets/details.json').subscribe(res=>this.alldetails=res 的请求)。看到使用 httpClient 你不需要使用 JSON.stringfy。 .json 必须在文件夹 assest 中(或在服务器中),因为当 angular-cli 构建项目时,您只会得到 index.html、一些“bundels 文件”(.js 和 css)和文件夹 assest。没有能力读取“localhost:4200/app/jsondata”

标签: angular angular2-forms


【解决方案1】:

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

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。此外,您还需要从 'Http @angular/http' 而不是 app.component.ts 中的 HttpClient

这是一个工作演示 - https://stackblitz.com/edit/angular2-notifications-example-gunqm4

【讨论】:

  • @gayathrin 哪个功能不起作用?你有什么错误吗?它对我来说很好。
  • stackblitz.com/edit/… 不工作..我无法获取 json 值
  • 我在等你的答复
  • @gayathrin 我可以看到示例中的下拉列表。你指的是哪个json数据?你在 UI 中显示数据吗?
  • @gayathrin 您需要删除 localhost api 路径并在您的 api 调用中使用“jsondata/details.json”。在此之前,您需要将“jsondata”文件夹添加到“app”内“assets”下的 angular-cli.json 文件中
猜你喜欢
  • 2017-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-19
  • 1970-01-01
  • 2017-09-12
  • 2015-12-27
  • 2017-03-08
相关资源
最近更新 更多