如何在Angular 2中获取JSON文件

Vis*_*shu 36 json angular

因为我是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>
Run Code Online (Sandbox Code Playgroud)

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 {
 }
Run Code Online (Sandbox Code Playgroud)

games.json

{
	"games":[
		{
			"title":"Primary Operations",
			"enabled":true
		},
		{
			"title":"Curated Games",
			"enabled":false
		}
	]
}
Run Code Online (Sandbox Code Playgroud)

我想将所有来自games.json的游戏带到app.component.ts的li中.请详细说明.

提前致谢

Bün*_*gül 57

以下是我解析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));

     }
}
Run Code Online (Sandbox Code Playgroud)


Hyd*_*hie 37

将json文件保存在Assets(与app dir并行)目录中

请注意,如果您使用ng new YourAppname生成 - 此资产目录与"app"目录存在相同的行,并且服务应该是app目录的子目录.可能如下所示:

::应用程序/服务/ 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);
} 
Run Code Online (Sandbox Code Playgroud)

  • 因为您的组件文件夹只能有四种类型的文件:1)'.html'2)'.css'或'.scss'3)'.specpec.ts'4)和'component.ts'文件.除了这四种类型之外,您无法添加任何其他类型,例如.json.其他类型的图像,例如:.png,.jpeg或.json需要保存在'app'文件夹之外. (3认同)

小智 11

如果使用angular-cli将json文件保存在Assets文件夹(与app dir并行)目录中

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);
}
Run Code Online (Sandbox Code Playgroud)

注意:这里你只需要在assets/json/oldjson.json之类的资源文件夹中给出路径,然后你需要编写像/json/oldjson.json这样的路径

如果你使用webpack,那么你需要在公共文件夹中遵循相同的结构,类似于assets文件夹.


Jan*_*ana 8

在Angular 5中

你可以说

this.http.get<Example>('assets/example.json')
Run Code Online (Sandbox Code Playgroud)

这会给你 Observable<Example>


Gil*_*ain 8

您不需要HttpClient,甚至不需要Angular。您只需要WebPack和JSON-Loader,它们都已成为Angular-CLI的一部分。

您需要的所有代码是这一行:

import * as someName from './somePath/someFile.json;
Run Code Online (Sandbox Code Playgroud)

并且您的json-data可以在下找到someName.default。但是,此代码将引发TypeScript编译器的类型错误-这不是真正的错误,而只是类型错误。

要解决该问题,请将此代码添加到您的src/typings.d.ts文件中(如果不存在,请创建它):

declare module "*.json"
{
  const value: any;
  export default value;
}
Run Code Online (Sandbox Code Playgroud)

请注意:使用此方法将在构建时将您的json(最小化/丑化)编译到应用包中。这意味着您将不需要等到该文件加载后就可以选择httpClient.get(...)应用程序,就像您选择使用它时一样。


Joh*_*ird 6

您需要对您进行HTTP调用games.json才能检索它.就像是:

this.http.get(./app/resources/games.json).map
Run Code Online (Sandbox Code Playgroud)