4

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"
    }
  }
}

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

10 Comments

Tried. Still the same issue.
Could you print the error message console.log(error) instead and post the output?
Object { headers: {…}, status: 404, statusText: "Not Found", url: "localhost:4200/assets/json/ucv_json.json", ok: false, name: "HttpErrorResponse", message: "Http failure response for localhost:4200/assets/json/ucv_json.json: 404 Not Found", error: "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Error</title>\n</head>\n<body>\n<pre>Cannot GET /assets/json/ucv_json.json</pre>\n</body>\n</html>\n" }
Are you sure the file is present in the location assets/json/ucv_json.json?
@Nosheep What protocol
|
1

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.