consume data from a JSON file in angular2 +

1

I need to get data from an external file, for example leave 2 service paths in an external file inside the assets folder, then from the servicio.ts get those URLs from the external file. is it possible to obtain data from an external file in angular 2 +?

if possible, do not use httpClient .

Thanks in advance

    
asked by Hersenfels 11.05.2018 в 04:51
source

2 answers

1

Without using httpClient the alternative is to import the json, transcribed from the original link because it is quite explanatory:

In ES6 / ES2015, you can import a json file directly into the code. For example,

example.json

{
    "name": "testing"
}

You can import it in ES6 / ES2015 in this way:

// ES6/ES2015
// app.js
import * as data from './example.json';
const word = data.name;
console.log(word); // output 'testing'

However, in Typescript, this code will give an error:

  

Can not find module 'example.json'

Solution: Use "Wildcard Module Name", add in the definitions file:

typings.d.ts

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

Then the import works like this

// Typescript
// app.ts
import * as data from './example.json';
const word = (<any>data).name;
console.log(word); // output 'testing'

references:

link

link

    
answered by 12.05.2018 / 00:18
source
0

with httpClient (tested and running):

getJson(){
 // puedes colocar esta funcion en tu servicio e injectando el servicio acceder
// a el desde cualquier componente
  let path = './assets/i18n/en.json';
  return this.http.get(path);
}
getMyFile(){
 //luego simplemente te suscribes a tu funcion cuando quieras obtener el json
// this.servicio.getJson().subscribe(data => {console.log(data)}) si la funcion
// se encuentra en el servicio
 getJson.subscribe(data => { console.log(data, 'tu json')} )
}

without httpClient (should work, not tested):

getJson(): Observable {
return this.http.get('./assets/i18n/en.json'))
    .map((response: Response) => {
        return response.json();
    }
)
.catch(this.handleError);
} 

Finally I would recommend going to httpClient, it is superior in all aspects, it reduces the number of code lines, it is more readable, it has more options, better documentation, and it is not difficult to go from one to the other.

    
answered by 11.05.2018 в 17:40