Angular 2/Angular 4:如何从本地系统位置访问文件? [英] Angular 2 / Angular 4 : How can i access file from the local system location?

查看:225
本文介绍了Angular 2/Angular 4:如何从本地系统位置访问文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的系统中以下位置有一个JSON文件

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

/etc/project/system.json

/etc/project/system.json

我正在尝试使用我的系统路径访问此文件,但是它不起作用.但是,如果我将此文件放在应用程序的 src 中,则可以正常工作.

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文件路径为"/etc/project/system.json",我的应用程序路径为"/var/www/DemoProject"

所以我该如何从本地系统访问文件.

So how can i access file from my local system.

推荐答案

正如其他人所述,您的问题只能由使用的服务器解决.通常,您想要的是静态文件服务.您可以在Internet上找到有关为服务器静态文件服务的具体说明.

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.

但是,您可能会在某个时候构建Angular应用程序.您甚至可能正在使用Webpack.

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

如果您使用Angular-cli来构建应用程序,则可以使用以下配置将系统文件夹复制到资产下.如果您使用Webpack,这还将在您每次请求时动态获取文件,而无需复制文件.在此处中了解有关webpack的信息.在您的.angular-cli.json文件中:

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

如果执行此操作,则可以使用URL http://yourdomain/<outputfolder>/system.json

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

如果您在打字稿代码中使用此json文件,则还可以设置打字稿路径映射配置来查找此文件. Webpack和Angular-cli也支持此配置.在您的tsconfig.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"
  ]
}

然后,您可以使用如下的打字稿导入json:

Then you can import the json in typescript like:

import * as data from 'system.json';

您必须对此json文件进行类型声明,因为typescript本身无法解析json文件的类型.您可以在此处中阅读.简而言之,将其放在项目根目录的typings.d.ts中:

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.

这篇关于Angular 2/Angular 4:如何从本地系统位置访问文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆