使用angular cli时访问放置在本地文件夹中的JSON [英] Access JSON placed in local folder when using angular cli

查看:19
本文介绍了使用angular cli时访问放置在本地文件夹中的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的项目使用 angular cli.我在如下结构中放置了一个 JSON

src/app/data/data.json.我正在尝试从 http.get 方法访问它

 返回 this._http.get('../data/data.json',{ 标头:this.getHeaders }).map((响应:响应) => response.json()).catch(this.handleError);

它说它找不到json.但是如果我将 JSON 放在 assets 文件夹中,它也可以工作.我不希望将 JSON 放置在资产文件夹中.如果我将 json 保留在 app 文件夹中,它会起作用吗?

解决方案

您需要使用 .angular-cli.json "assets" 部分.这样,您将通过 angular cli 获得静态资产输出,例如:

资产":[资产","favicon.ico",应用程序/数据/数据.json"],

通过在 assets 中指定 app/data/data.json cli 将只输出一个文件 data.jsonapp/data/ 文件夹.如果您想输出 app/data 文件夹中的所有资产,请执行以下操作:

资产":[资产","favicon.ico",应用程序数据"],

<块引用>

您可以随时检查您的 static 资产是否被 cli 输出运行 ng build 并检查 dist 文件夹的内容.

您可以将自定义资产放入 assets 中,例如assets/data/data.json 这样你就不用修改了.angular-cli.json as assets 文件夹默认已经存在

I am using angular cli for my projects. I have placed a JSON in structure like below

src/app/data/data.json. I am trying to access it from http.get method

 return this._http.get('../data/data.json',
                              { headers: this.getHeaders })
            .map((response: Response) => response.json())
            .catch(this.handleError);

It say it cannot find the json. But same if i place JSON in assets folder it works. I dont want JSON to be placed in assets folder. Will it work if i keep the json in app folder?

解决方案

You need to use .angular-cli.json "assets" section. This way you will get your static assets output by angular cli e.g:

"assets": [
    "assets",
    "favicon.ico",
    "app/data/data.json"
 ],

By specifying app/data/data.json in assets cli will output just a single file data.json in to app/data/ folder. If you want to output all assets inside your app/data folder then you do this:

"assets": [
        "assets",
        "favicon.ico",
        "app/data"
     ],

You can always check if your static assets getting outputed by cli by running ng build and checking the content of the dist folder.

You can place you custom assets in to assets like assets/data/data.json so this way you do not have to modify .angular-cli.json as assets folder is already there by default

这篇关于使用angular cli时访问放置在本地文件夹中的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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