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

标签 angular typescript angular5

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

/etc/project/system.json

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

JSON 文件路径是“/etc/project/system.json”,我的应用程序路径是“/var/www/DemoProject”

那么如何从我的本地系统访问文件呢?

最佳答案

正如其他人所说,您的问题只能由您使用的服务器来解决。您想要的通常是命名的静态文件服务。您可以在互联网上找到有关为您的服务器提供静态文件服务的具体说明。

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

如果您使用 Angular-cli 构建您的应用程序,您可以使用以下配置将系统文件夹复制到您的 Assets 下。如果您使用 Webpack,这也会在您每次请求时动态获取文件,而无需复制文件。阅读有关 webpack 的信息 here .在你的.angular-cli.json文件:

"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 访问该文件

如果你在你的 typescript 代码中使用这个 json 文件,你也可以设置 typescript 路径映射配置来找到这个文件。 Webpack 和 Angular-cli 也支持这种配置。在你的tsconfig.json文件:

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

然后你可以在 typescript 中导入 json,比如:

import * as data from 'system.json';

你必须有这个 json 文件的类型声明,因为 typescript 不能自己解析 json 文件的类型。你可以阅读它here .简而言之,把它放在 typings.d.ts 中在您的项目根目录中:

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

您可以阅读更多关于 typescript 路径解析的信息 here .

关于 Angular 2/Angular 4 : How can I access file from the local system location?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46470453/

相关文章:

angular5 - ngFor - 从循环中获取项目以在函数中调用它

angular - 如何使用 NgModule 导出 const

html - Angular2 @ViewChild ElementRef offsetHeight 始终为 0

typescript - 用基类装饰器扩展组件装饰器

node.js - 在 Angular (>= 2) 应用程序中,如何将 npm package.json 文件中的版本信息包含到编译的输出文件中?

javascript - 有条件地在基类上指定方法/ Prop

javascript - 如何跟踪 Angular 中一个组件中另一个组件中发出的值的变化

typescript - 如何从 github 存储库安装 typescript 定义

javascript - 删除后 knockout View 不会从 View 中删除项目

angular - 使用 angular2-logger 的 Angular 5 项目中的错误