简体   繁体   中英

Unable to read the json files which is located in any folder different from assets folder in Angular 2/4

Trying to read a json file with http.get in Angular 4 project using the following script.

http.get('../jsonmock/data.json')
.subscribe(res  =>  this.data = res.json() );

If I try to read the json file from assets folder it runs successfully but from any other folder I got the following error on console

http.get('../jsonmock/data.json') .subscribe(res => this.data = res.json() );

Response {_body: "↵↵↵↵↵↵", status: 404, ok: false, statusText: "Not Found", headers: Headers, …} headers : Headers {_headers: Map(8), _normalizedNames: Map(8)} ok : false status : 404 statusText : "Not Found" type : 2 url : " http://localhost:4200/jsonmock/data.json " _body : "↵↵↵↵Error↵↵↵

Cannot GET /jsonmock/data.json
↵↵↵" proto : Body constructor : ƒ Response(responseOptions) arguments : (...) caller : (...) length : 1 name : "Response" prototype : Body {constructor: ƒ, toString: ƒ} proto : ƒ Body() [[FunctionLocation]] : http.es5.js:900 [[Scopes]] : Scopes[3] toString : ƒ ()

If you are using the Angular CLI ... it will only look for assets in the folders you tell it to in the .angular-cli.json file.

In the "apps" node there is a node called "assets":

  "assets": [
    "assets",
    "api",
    "favicon.ico"
  ],

By default, only the assets and the favicon are here. If you want it to look in other locations for your .json file, you need to specify those locations here, as I did with the api folder.

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