因为我是Angular的新手,所以有人可以提供一个简单的解决方案来使用angular 2加载JSON文件数据。
我的代码如下
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
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":[ { "title":"Primary Operations", "enabled":true }, { "title":"Curated Games", "enabled":false } ] }
我想将所有游戏从games.json提取到app.component.ts的li中,请详细告知。
这是我解析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)); } }