加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何在Angular 2中获取JSON文件

发布时间:2020-12-17 08:03:23 所属栏目:安全 来源:网络整理
导读:因为我是Angular的新手,任何人都可以提供一个简单的解决方案,使用angular 2加载JSON文件数据。 我的代码如下 的index.html html head titleAngular 2 QuickStart/title meta charset="UTF-8" meta name="viewport" content="width=device-width,initial-sc
因为我是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));

     }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读