简体   繁体   中英

Can't read data from JSON file in local folder in Angular 7

I have the below code and it works fine.

 searchData() {
 const url: any = 'https://jsonplaceholder.typicode.com/photos?albumId=1';
 this.http.get(url).subscribe((res) => {
 this.data = res;
 console.log('Response Returned');
 },
  err => {
    console.log('Error Response');
  });

Output: Response Returned Expected: Response Returned

Now instead of URL, I want to fetch data from a local JSON file which is kept in the assets folder, so I changed the path and gave the path of the JSON file, however, if I give local path the code goes to err part and in response, I get Error Response. Can someone help me figure out how to read from a local JSON file?

Code for Local JSON file

searchData() {
     const ucv_data: any = 'src/assets/json/ucv_json.json';
    this.http.get(ucv_data).subscribe((res) => {
      this.data = res;
      console.log('Response Returned');
    },
      err => {
        console.log('Error Response');
      }
    );
 }

Output: Error Response Expected: Response Returned

Angular.json file

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "test-ng7": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist",
            "index": "src/index.html",
            "main": "src/main.ts",
            "tsConfig": "src/tsconfig.app.json",
            "polyfills": "src/polyfills.ts",
            "assets": [
              "src/assets/json",
              "src/assets/images",
              "src/favicon.ico"
            ],
            "styles": [
              "./node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css",
              "./node_modules/bootstrap/dist/css/bootstrap.min.css",
              "./node_modules/font-awesome/css/font-awesome.css",
              "./node_modules/font-awesome/css/font-awesome.min.css",
              "src/styles/app.scss","src/assets/css/material.scss",
              "src/assets/css/styles.scss"

            ],
            "scripts": [
              "node_modules/chart.js/dist/Chart.js",
              "./node_modules/jquery/dist/jquery.min.js",
              "./node_modules/bootstrap/dist/js/bootstrap.min.js"

            ]
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "test-ng7:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "test-ng7:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "test-ng7:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "karmaConfig": "src/karma.conf.js",
            "scripts": [
              "node_modules/chart.js/dist/Chart.js"
            ],
            "styles": [
              "./node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css",
              "node_modules/font-awesome/css/font-awesome.css",
              "src/styles/app.scss"
            ],
            "assets": [
              "src/assets",
              "src/assets/images",
              "src/favicon.ico"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "test-ng7-e2e": {
      "root": "e2e/",
      "projectType": "application",
      "prefix": "",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "test-ng7:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "test-ng7:serve:production"
            }
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": "e2e/tsconfig.e2e.json",
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  },
  "defaultProject": "test-ng7",
  "schematics": {
    "@schematics/angular:component": {
      "prefix": "app",
      "styleext": "scss"
    },
    "@schematics/angular:directive": {
      "prefix": "app"
    }
  }
}

The path is relative from the src folder. Try

const ucv_data: any = 'assets/json/ucv_json.json';

Update

Based on the OP's comment, the assets property definition is

"assets": [ 
  "src/assets/json", 
  "src/assets/images", 
  "src/favicon.ico" 
]

So the call should be made to location /json/ucv_json.json .

With Angular 7+ we can import JSON like modules.

In tsconfig file put:

{  "compilerOptions": {  "resolveJsonModule": true, "esModuleInterop": true } }

And you can import it like this afterwords.

import ucv_data from "assets/json/ucv_json.json"

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