如何在Angular 2中获取JSON文件 [英] How to fetch JSON file in Angular 2
本文介绍了如何在Angular 2中获取JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
由于我是Angular的新手,任何人都可以提供一个简单的解决方案,以使用angular 2加载JSON文件数据.
as I am new to the Angular, can anyone please give a simple solution on loading the JSON file data using angular 2.
我的代码如下
Index.html
Index.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
games.json
{
"games":[
{
"title":"Primary Operations",
"enabled":true
},
{
"title":"Curated Games",
"enabled":false
}
]
}
我想将所有游戏从games.json提取到app.component.ts的li中 请详细告知.
I want to fetch all games from games.json into li at app.component.ts Please advise in detail.
推荐答案
这是我解析JSON的代码的一部分,对您可能会有帮助:
Here is a part of my code that parse JSON, it may be helpful for you:
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));
}
}
这篇关于如何在Angular 2中获取JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文