-1

I have a function that gets the data from a saved file into the myJson variable. How can I check that the file exists without it affecting the below methods? Also, the file is in another folder that the one of the src of the project. It is in the backend dedicated folder. How can I access it from Angular and also to check if the file exists?

import myJson from 'src/assets/myFile.json' ;

readFile() {
  this.savedData=myJson;
  console.log("this is data from file "+this.savedData);
  return myJson;
}
constructor (){
    this.savedData= this.readFile();
  }

Viktor
  • 79
  • 1
  • 8
  • 1
    You should use the `get` method from http. If the file doesn't exists you will simply get an error that you can catch easily. – Jacopo Sciampi Mar 01 '21 at 14:36
  • @JacopoSciampi but if I use the http get method, I should use an observable and the data won't be available instantly. How can I solve this instant issue with the data? – Viktor Mar 01 '21 at 14:59
  • You can use the `toPromise` method along with `await` in an async function. This way you will be synchronous, meaning that if you have other code after the function that gets the file, the data will be available and ready. – Jacopo Sciampi Mar 01 '21 at 15:03
  • For the BE part: when you host your Backend you can make a simple API that return the file, then use the same `get` method to get the file's content. Sadly I can't help you more than this in the BE's stuff since I've no experience in it. – Jacopo Sciampi Mar 01 '21 at 15:04
  • @JacopoSciampi can you help with the toPromise and await please? – Viktor Mar 01 '21 at 15:11

1 Answers1

1

Giving more context to my comments, I would do the async function as follow:

public async readFile() {
  return await new Promise((resolve,reject) => {
    this.http.get("your_path_to_file").toPromise().then(res => {
      resolve(res);
    }).catch(err => {
      reject(err);
    });
  });
}

Then the funcion that calls the readFile :

public getFile() {
  this.saveData = this.readFile();
  // more code here if needed
}

Then instead of calling it in the constructor I'd use the OnInit life cycle:

public ngOnInit(): void {
  this.getFile();
}

More datails on why it's a bad practise to return a promise in the constructor here: Is it bad practice to have a constructor function return a Promise?

Jacopo Sciampi
  • 2,990
  • 1
  • 20
  • 44
  • Thank you. The problem is that I need the data instantly, because some methods that use this data are running before the promise finishing. The data is static, is available in the file, how can I read it instantly, without the delays that the promise has? – Viktor Mar 02 '21 at 08:47
  • Sadly, in this case, you can't. Reading json data (from a file or from an API) requires an asynchronous approach. – Jacopo Sciampi Mar 02 '21 at 09:30