0

Hi I'm kinda new in Angular and I have the 7 version. I'm writing an application and I want to know if it's possible to bind a JSON file to a variable.

I have a class like this:

export class Aparment {

  id: number;
  address: string;

  constructor(id: number, address: string) {
     this.id = id;
     this.address = address;
  }

} 

In a component I have an array of Apartment and I push some apartment objects in it. What I'm looking for is a way to read all apartment objects stored in a file in /assets/json/apartments.json when I run the application and add an apartment objet into the json file when I push a new object into the array. So far I've read that from typescript 2.9+ we can import and use a json file, but I don't know how to cast it as an array of Apartment and I don't know how to store new elements into it.

GJCode
  • 1,959
  • 3
  • 13
  • 30
  • 3
    Using straight angular, it is **not possible** to automatically modify the contents of a local file on the client's file system. If you could, this would be a **huge** security flaw. To do this, you'll need some sort of server to handle the file manipulation or a UI element to save the file manually. See [here](https://stackoverflow.com/questions/30288087/is-it-possible-to-write-data-to-a-locally-json-file-with-nothing-but-angular) for more info. – Rich Apr 24 '19 at 16:46
  • However, it is possible to read in from a JSON and parse the file automatically into a class, so long as you provide the relevant data in the constructor. – Rich Apr 24 '19 at 16:47
  • @Rich you're right, you know when you're learning something new and forgot the foundamentals, this would be of course a security issue...thanks – GJCode Apr 24 '19 at 16:56

0 Answers0