简体   繁体   中英

Where to put the JSON file in the Angular Project?

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: 在此处输入图像描述

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.

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, ie 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 '../'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM