从组件(Angular)中的资产目录导入静态JSON文件 [英] Import static JSON file from assets dir in component (Angular)
问题描述
我正在使用Angular CLI(版本6).我的 assets
文件夹中有一个小的 JSON
文件,我想将其导入到组件中.我想使用来自组件的GET请求不使用来完成此操作.
I am using Angular CLI (version 6).
I have a small JSON
file in my assets
folder which I want to import into my component. I want to do this without using a GET request from my component.
我做了什么:
-
我创建了一个新文件
typings.d.ts
:
declare module "*.json" {
const value: any;
export default value;
}
...,并在 tsconfig.spec.json
中对其进行了引用.这是 ts.config.spec.json
中引荐的摘录:
... and referred to it in tsconfig.spec.json
. Here is a snippet of the referral in ts.config.spec.json
:
"files": [
"test.ts",
"polyfills.ts",
"./typings.d.ts"
],
我正在尝试从组件中导入JSON文件,
From my component, I am trying to import my JSON file as such:
import * as myConfig from '../../assets/config.json';
但是在那一行,我收到一条错误消息:找不到模块../../assets/config.json
.
At that line however, I get an error message: cannot find module ../../assets/config.json
.
我非常确定这个相对路径是正确的(我也尝试了其他几个选项,对于types.d.ts引用也是如此-但无论如何,我的目录结构只是一个简单的Angualr CLI应用程序:
I am quite sure that this relative path is correct (I tried several other options as well, similarly for the typings.d.ts referral - but anyway, my directory structure is just a simple Angualr CLI app:
|- src
|
|-app
| |-component
| |-component.ts
|
|
|-assets
|-config.json
任何有关解决此问题的技巧将不胜感激.
Any tips on how to solve this problem would be greatly appreciated.
推荐答案
您只需从"path/to/json"导入myConfig
,然后在文件中使用它即可.
You can just import myConfig from 'path/to/json'
then use it in your file.
这篇关于从组件(Angular)中的资产目录导入静态JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!