简体   繁体   English

无法从 Angular 的本地文件夹中的 JSON 文件中读取数据 7

[英]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 Output:响应返回预期:响应返回

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.现在,我想从保存在 assets 文件夹中的本地 JSON 文件中获取数据,而不是 URL,所以我更改了路径并给出了 Z0ECD11C1D7A287401D148A23BBD7 文件的路径作为回应,我得到错误响应。 Can someone help me figure out how to read from a local JSON file?有人可以帮我弄清楚如何从本地 JSON 文件中读取吗?

Code for Local JSON file本地 JSON 文件的代码

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 Output:预期错误响应:返回响应

Angular.json file Angular.json文件

{
  "$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.该路径是相对于src文件夹的。 Try尝试

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

Update更新

Based on the OP's comment, the assets property definition is根据 OP 的评论, assets属性定义是

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

So the call should be made to location /json/ucv_json.json .所以应该调用位置/json/ucv_json.json

With Angular 7+ we can import JSON like modules.使用 Angular 7+ 我们可以导入 JSON 之类的模块。

In tsconfig file put:在 tsconfig 文件中放置:

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

And you can import it like this afterwords.然后你可以像这样导入它。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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