Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - how to fill a local variable with JSON data from an external file

Tags:

The Angular 2 tutorials I have read place variables directly in the app.component.ts file. For example var BAR below, which pulls data though the {Foo} interface.

import {Component} from 'angular2/core'; import {Foo} from './foo';  @Component({    etc. });  export class AppComponent {    bar = BAR; }  var BAR: Foo[] = [    { 'id': 1 },    { 'id': 2 } ]; 

However, I have the data for BAR in a local JSON file. I don't believe {HTTP_PROVIDER} is necessary. How would I go about getting the JSON data from the external file?

like image 781
ebakunin Avatar asked Mar 21 '16 23:03

ebakunin


People also ask

How do I add data to a local JSON file?

To write this new data to our JSON file, we will use fs. writeFile() which takes the JSON file and data to be added as parameters. Note that we will have to first convert the object back into raw format before writing it. This will be done using JSON.


1 Answers

Create a file with this content

export const BAR= [ { 'id': 1 }, { 'id': 2 } ];

save it as BarConfig.ts or some like

later use it as follows

import { BAR } from './BarConfig'; let bar= BAR;

or even better, use BAR directly where you needed

like image 142
William Ardila Avatar answered Sep 25 '22 00:09

William Ardila