Cómo obtener un archivo JSON en Angular 2


Como soy nuevo en Angular, puede alguien por favor dar una solución simple al cargar los datos del archivo JSON usando angular 2.

Mi código es como abajo

Índice.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.componente.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 {
 }

Juegos.json

{
	"games":[
		{
			"title":"Primary Operations",
			"enabled":true
		},
		{
			"title":"Curated Games",
			"enabled":false
		}
	]
}

Quiero recuperar todos los juegos de games.json en li en la aplicación.componente.ts Por favor avise en detalle.

Gracias de antemano

Author: Vishu, 2016-09-09

9 answers

Aquí hay una parte de mi código que analiza JSON, puede ser útil para usted:

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));

     }
}
 44
Author: Bünyamin Sarıgül,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-09 11:41:07

Mantener el archivo json en el directorio Assets (paralelo a app dir)

Tenga en cuenta que si hubiera generado con ng new YourAppname - este directorio de activos existe la misma línea con el directorio 'app', y los servicios deben ser el directorio hijo del directorio de aplicaciones. Puede verse como a continuación:

:: app / services / 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);
} 
 35
Author: HydTechie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-21 12:06:05

Si utiliza angular-cli, Mantenga el archivo json dentro de la carpeta Assets (paralela a app dir) directorio

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);
}

Nota: aquí solo necesita dar la ruta dentro de la carpeta assets como assets/json/oldjson.json entonces necesitas escribir path como/json / oldjson.json

Si utiliza webpack, debe seguir la misma estructura anterior dentro de la carpeta pública, su carpeta similar como assets.

 10
Author: Vijay Gajera,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-09 06:29:53

En Angular 5

Solo puedes decir

this.http.get<Example>('assets/example.json')

Esto te dará Observable<Example>

 7
Author: Jana,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-14 10:18:27

Necesita hacer una llamada HTTP a su games.json para recuperarlo. Algo como:

this.http.get(./app/resources/games.json).map
 6
Author: John Baird,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-17 14:25:03

Creo que la carpeta assets es pública, puede acceder a ella directamente en el navegador

Http://localhost:4020/assets/

A diferencia de otras carpetas privadas, suelte su archivo json en la carpeta assets

 2
Author: Anthony Agbator,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-16 07:51:05
service.service.ts
--------------------------------------------------------------

import { Injectable } from '@angular/core';
import { Http,Response} from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';

@Injectable({
  providedIn: 'root'
})
export class ServiceService {
 private url="some URL";

constructor(private http:Http) { }     

//getData() is a method to fetch the data from web api or json file

getData(){
           getData(){
          return this.http.get(this.url)
            .map((response:Response)=>response.json())
        }
          }
}






display.component.ts
--------------------------------------------

//En este componente obtiene los datos usando suscribe() y los almacena en el objeto local como DataObject y muestra los datos en display.componente.html como {{DataObject .propertyName}}.

import { Component, OnInit } from '@angular/core';
import { ServiceService } from 'src/app/service.service';

@Component({
  selector: 'app-display',
  templateUrl: './display.component.html',
  styleUrls: ['./display.component.css']
})
export class DisplayComponent implements OnInit {
      dataObject :any={};
constructor(private service:ServiceService) { }

  ngOnInit() {
    this.service.getData()
      .subscribe(resData=>this.dataObject =resData)
}
}
 1
Author: Raviraj S Kharvi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-05 05:05:15

No necesitas HttpClient, ni siquiera necesitas Angular. Todo lo que necesita es WebPack y JSON-Loader, ambos ya forman parte de Angular-CLI.

Todo el código que necesitas es esta línea:

import * as someName from './somePath/someFile.json;

Y los datos de su json se pueden encontrar en someName.default. Sin embargo, este código lanzará un error de tipo desde el compilador de TypeScript-esto no es un error real, sino solo un error de tipo.

Para resolverlo agregue este código a su archivo src/typings.d.ts (si no existe, cree it):

declare module "*.json"
{
  const value: any;
  export default value;
}

Tenga en cuenta: que trabajar en este método compilará su json (minify/uglify) en el paquete de aplicaciones en el momento de la compilación. Esto significa que no tendrá que esperar hasta que se cargue este archivo, como lo hará si elige trabajar con httpClient.get(...), ¡lo que significa una aplicación más rápida!

 1
Author: Gil Epshtain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-02 13:34:18

Necesitaba cargar el archivo de configuración de forma sincrónica, y esta fue mi solución:

export function InitConfig(config: AppConfig) { return () => config.load(); }

import { Injectable } from '@angular/core';

@Injectable()
export class AppConfig {
    Settings: ISettings;

    constructor() { }

    load() {
        return new Promise((resolve) => {
            this.Settings = this.httpGet('assets/clientsettings.json');
            resolve(true);
        });
    }

    httpGet(theUrl): ISettings {
        const xmlHttp = new XMLHttpRequest();
        xmlHttp.open( 'GET', theUrl, false ); // false for synchronous request
        xmlHttp.send( null );
        return JSON.parse(xmlHttp.responseText);
    }
}

Esto se proporciona como un app_initializer que se carga antes que el resto de la aplicación.

App.módulo.ts

{
      provide: APP_INITIALIZER,
      useFactory: InitConfig,
      deps: [AppConfig],
      multi: true
    },
 0
Author: jonas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-06 05:47:32