Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
811 views
in Technique[技术] by (71.8m points)

typescript - Angular 2 / Angular 4 : How can I access file from the local system location?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...