如何在Angular 2中获取JSON文件

前端之家收集整理的这篇文章主要介绍了如何在Angular 2中获取JSON文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
因为我是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
		}
	]
}

我想从app.component.ts获取所有来自games.json的游戏到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));

     }
}
原文链接:https://www.f2er.com/angularjs/143977.html

猜你在找的Angularjs相关文章