Estoy usando Angular 5 y he creado un servicio usando angular-cli
Lo que quiero hacer es crear un servicio que lea un archivo json local para Angular 5.
Esto es lo que tengo... estoy un poco atascado...
import { Injectable } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; @Injectable() export class AppSettingsService { constructor(private http: HttpClientModule) { var obj; this.getJSON().subscribe(data => obj=data, error => console.log(error)); } public getJSON(): Observable<any> { return this.http.get("./assets/mydata.json") .map((res:any) => res.json()) .catch((error:any) => console.log(error)); } }¿Cómo puedo terminar esto?
Primero, debe inyectar HttpClient y Not HttpClientModule , en segundo lugar, debe eliminar .map((res:any) => res.json()) ya no lo necesitará porque el nuevo HttpClient le dará el cuerpo de la respuesta por defecto, finalmente asegúrese de importar HttpClientModule en su AppModule :
import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable() export class AppSettingsService { constructor(private http: HttpClient) { this.getJSON().subscribe(data => { console.log(data); }); } public getJSON(): Observable<any> { return this.http.get("./assets/mydata.json"); } }para agregar esto a su Componente:
@Component({ selector: 'mycmp', templateUrl: 'my.component.html', styleUrls: ['my.component.css'] }) export class MyComponent implements OnInit { constructor( private appSettingsService : AppSettingsService ) { } ngOnInit(){ this.appSettingsService.getJSON().subscribe(data => { console.log(data); }); } }Para Angular 7, seguí estos pasos para importar directamente datos json:
En tsconfig.app.json:
agregue "resolveJsonModule": true en "compilerOptions"
En un servicio o componente:
import * as exampleData from '../example.json';Y luego
private example = exampleData;Tiene una solución alternativa, importando directamente su json.
Para compilar, declara este módulo en tu archivo typings.d.ts
declare module "*.json" { const value: any; export default value; }en tu codigo
import { data_json } from '../../path_of_your.json'; console.log(data_json)