Angular 2 / Angular 4 : How can i access file from the local system location?

Pinank Lakhani picture Pinank Lakhani · Sep 28, 2017 · Viewed 28.7k times · Source

I have one JSON file at the following location in my system

/etc/project/system.json

I'm trying to access this file using my system path but it's not working. However it's working fine if i put this file inside src in my application.

JSON File path is "/etc/project/system.json" and my application path is "/var/www/DemoProject"

So how can i access file from my local system.

Answer

Gökhan Kurt picture Gökhan Kurt · Oct 5, 2017

As others stated, your problem can only be solved by the server you are using. What you want is generally named, static file serving. You can find specific instructions for static file serving for your server in the internet.

However, you are probably building your Angular application at some point. You might even be using Webpack.

If you are using Angular-cli to build your app, you can use following configuration to copy the system folder under your assets. If you use Webpack, this will also dynamically fetch the file everytime you request, without copying the file. Read about webpack here. In your .angular-cli.json file:

"assets": [
  "assets",            // These two are generally used in Angular projects
  "favicon.ico",       // ^^^^^^^^^
  {
    "glob": "system.json",
    "input": "/etc/project/",
    "output": "./<outputfolder>"
  }
]

If you do this, you can access the file with the url http://yourdomain/<outputfolder>/system.json

If you are using this json file in your typescript code, you can also set typescript path mapping configuration to find this file. Webpack and Angular-cli also supports this configuration. In your tsconfig.json file:

"paths": {
  "system.json": [
    "/etc/project/system.json"
  ]
}

Then you can import the json in typescript like:

import * as data from 'system.json';

You must have type declaration for this json file as typescript can't resolve types of json files by itself. You can read about it here. In short, put this in typings.d.ts in your project root:

declare module "*.json" {
    [key: string]: any;
}

You can read more about typescript path resolving here.