如何在 Angular 2 中获取 JSON 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39406043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to fetch JSON file in Angular 2
提问by Vishu
as I am new to the Angular, can anyone please give a simple solution on loading the JSON file data using angular 2.
由于我是 Angular 的新手,任何人都可以提供一个使用 angular 2 加载 JSON 文件数据的简单解决方案吗?
My code is like below
我的代码如下
Index.html
索引.html
<html>
<head>
<title>Angular 2 QuickStart</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/styles.css">
<!-- 1. Load libraries -->
<!-- Polyfill(s) for older browsers -->
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<!-- 2. Configure SystemJS -->
<script src="systemjs.config.js"></script>
<script>
System.import('app').catch(function(err){ console.error(err); });
</script>
</head>
<!-- 3. Display the application -->
<body>
<my-app>Loading...</my-app>
</body>
</html>
app.component.ts
app.component.ts
import {Component} from '@angular/core';
@Component({
selector: 'my-app',
template: `
<div id="main">
Main Div
<div id = "header"></div>
<div id = "content">
<ul class="games">
<li>
</li>
</ul>
</div>
</div>
`
})
export class AppComponent {
}
games.json
游戏.json
{
"games":[
{
"title":"Primary Operations",
"enabled":true
},
{
"title":"Curated Games",
"enabled":false
}
]
}
I want to fetch all games from games.json into li at app.component.ts Please advise in detail.
我想把games.json里的所有游戏都取到app.component.ts里的li里,请详细指教。
回答by Bünyamin Sar?gül
Here is a part of my code that parse JSON, it may be helpful for you:
这是我解析 JSON 的代码的一部分,它可能对您有所帮助:
import { Component, Input } from '@angular/core';
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class AppServices{
constructor(private http: Http) {
var obj;
this.getJSON().subscribe(data => obj=data, error => console.log(error));
}
public getJSON(): Observable<any> {
return this.http.get("./file.json")
.map((res:any) => res.json())
.catch((error:any) => console.log(error));
}
}
回答by HydTechie
Keep the json file in Assets (parallel to app dir) directory
将 json 文件保存在 Assets(与应用程序目录平行)目录中
Note that if you would have generated with ng new YourAppname- this assets directory exists same line with 'app' directory, and services should be child directory of app directory. May look like as below:
请注意,如果您使用 ng new YourAppname 生成 - 此资产目录与“app”目录存在同一行,并且服务应该是应用程序目录的子目录。可能如下所示:
::app/services/myservice.ts
::应用程序/服务/myservice.ts
getOrderSummary(): Observable {
// get users from api
return this.http.get('assets/ordersummary.json')//, options)
.map((response: Response) => {
console.log("mock data" + response.json());
return response.json();
}
)
.catch(this.handleError);
}
回答by Vijay Gajera
If you using angular-cli Keep the json file inside Assets folder (parallel to app dir) directory
如果您使用 angular-cli 将 json 文件保存在 Assets 文件夹(与应用程序目录平行)目录中
return this.http.get('<json file path inside assets folder>.json'))
.map((response: Response) => {
console.log("mock data" + response.json());
return response.json();
}
)
.catch(this.handleError);
}
Note: here you only need to give path inside assets folder like assets/json/oldjson.json then you need to write path like /json/oldjson.json
注意:这里你只需要在assets/json/oldjson.json之类的assets文件夹中提供路径然后你需要像/json/oldjson.json这样写路径
If you using webpack then you need to follow above same structure inside public folder its similar like assets folder.
如果您使用 webpack,那么您需要在公共文件夹中遵循上述相同的结构,其类似于资产文件夹。
回答by Jana
In Angular 5
在 Angular 5
you can just say
你可以说
this.http.get<Example>('assets/example.json')
This will give you Observable<Example>
这会给你 Observable<Example>
回答by Gil Epshtain
You don't need HttpClient, you don't even need Angular. All you need is WebPack and JSON-Loader, both are already part of Angular-CLI.
你不需要HttpClient,你甚至不需要 Angular。你所需要的只是 WebPack 和 JSON-Loader,两者都已经是 Angular-CLI 的一部分。
All the code you need is this line:
您需要的所有代码就是这一行:
import * as someName from './somePath/someFile.json;
And the your json-data can be found under someName.default. However this code will throw a type-error from the TypeScript compiler - this isn't a real error, but only a type-error.
您的 json-data 可以在someName.default. 然而,这段代码会从 TypeScript 编译器中抛出一个类型错误——这不是一个真正的错误,而只是一个类型错误。
To solve it add this code to your src/typings.d.tsfile (if it doesn't exist create it):
要解决它,请将此代码添加到您的src/typings.d.ts文件中(如果它不存在,请创建它):
declare module "*.json"
{
const value: any;
export default value;
}
Please notice: that working in this method will compile your json (minify/uglify) into the app bundle at build time. This mean that you won't need to wait until this file will load - as you will if you choice to work with httpClient.get(...)- meaning faster application!
请注意:使用此方法将在构建时将您的 json (minify/uglify) 编译到应用程序包中。这意味着您无需等到此文件加载 - 如果您选择使用httpClient.get(...)- 这意味着更快的应用程序!
回答by John Baird
You need to make an HTTPcall to your games.jsonto retrieve it.
Something like:
您需要对您进行HTTP调用games.json以检索它。就像是:
this.http.get(./app/resources/games.json).map
回答by Anthony Agbator
i think the assets folder is public, you can access it directly on the browser
我认为资产文件夹是公开的,您可以直接在浏览器上访问它
unlike other privates folders, drop your json file in the assets folder
与其他 privates 文件夹不同,将您的 json 文件放在 assets 文件夹中
回答by jonas
I needed to load the settings file synchronously, and this was my solution:
我需要同步加载设置文件,这是我的解决方案:
export function InitConfig(config: AppConfig) { return () => config.load(); }
import { Injectable } from '@angular/core';
@Injectable()
export class AppConfig {
Settings: ISettings;
constructor() { }
load() {
return new Promise((resolve) => {
this.Settings = this.httpGet('assets/clientsettings.json');
resolve(true);
});
}
httpGet(theUrl): ISettings {
const xmlHttp = new XMLHttpRequest();
xmlHttp.open( 'GET', theUrl, false ); // false for synchronous request
xmlHttp.send( null );
return JSON.parse(xmlHttp.responseText);
}
}
This is then provided as a app_initializer which is loaded before the rest of the application.
然后将其作为 app_initializer 提供,它在应用程序的其余部分之前加载。
app.module.ts
app.module.ts
{
provide: APP_INITIALIZER,
useFactory: InitConfig,
deps: [AppConfig],
multi: true
},
回答by Raviraj S Kharvi
service.service.ts
--------------------------------------------------------------
import { Injectable } from '@angular/core';
import { Http,Response} from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
@Injectable({
providedIn: 'root'
})
export class ServiceService {
private url="some URL";
constructor(private http:Http) { }
//getData() is a method to fetch the data from web api or json file
getData(){
getData(){
return this.http.get(this.url)
.map((response:Response)=>response.json())
}
}
}
display.component.ts
--------------------------------------------
//In this component get the data using suscribe() and store it in local object as dataObject and display the data in display.component.html like {{dataObject .propertyName}}.
//在这个组件中使用 suscribe() 获取数据并将其作为 dataObject 存储在本地对象中,并将数据显示在 display.component.html 中,如 {{dataObject .propertyName}}。
import { Component, OnInit } from '@angular/core';
import { ServiceService } from 'src/app/service.service';
@Component({
selector: 'app-display',
templateUrl: './display.component.html',
styleUrls: ['./display.component.css']
})
export class DisplayComponent implements OnInit {
dataObject :any={};
constructor(private service:ServiceService) { }
ngOnInit() {
this.service.getData()
.subscribe(resData=>this.dataObject =resData)
}
}
回答by Boris Yakubchik
For example, in your component before you declare your @Component
例如,在您声明@Component之前的组件中
const en = require('../assets/en.json');

