Reputation: 73
I want to open the JSON file I created. The source code that is reading the JSON file is in node_modules directory. I tried putting the JSON file in a common directory (same level as src) but the following error keeps on showing: The requested resource is not found in this server.
TS file reading the JSON file:
openJSONFile() {
let xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let jsonObj = JSON.parse(this.responseText)
console.log(jsonObj);
}
}
xmlHttp.open("GET", "../../../../../../../../../common/branch_code_branch_name.json", true);
xmlHttp.send();
}
Location of branch_code_branch_name.json:
Upvotes: 0
Views: 2846
Reputation: 1884
Place your JSON file inside the folder Assets
that's been created for you when you started a new project with Angular.
Ideally, place additionally directories here to make it easier in the future, i.e. Create some directories like, css
, scss
, js
, images
, json
, or even mock-data
Then, place your JSON file in the appropriately labelled, json
directory.
When referencing this file, ensure the number of "../" that you place, represent the accurate number of directories UP you want to access.
For example, if I have a ts file, and it's found in:
app->users->services->user-service
And it needs to reference a json file in the aforementioned location, then I would use:
'../../../assets/json/nameofmyjsonfile.json'
If my ts file was TWO more levels deep, it would look like this:
'../../../../../assets/json/nameofmyjsonfile.json'
Additionally, you can look into "relative" referencing, to avoid many '../'
Upvotes: 1
Reputation: 86740
Assets
folder is created for such data in Angular project.
assets - Contains image and other asset files to be copied as-is when you build your application.
All the static data including your images/Css files/JSON/ or JS files you can include in this folder.
Upvotes: 1