简体   繁体   English

Angular2加载图片

[英]Angular2 load image

I have a problem with including images, script or css in app with angular2. 我在用angular2的应用程序中包含图像,脚本或css时遇到问题。 I have image in folder /app-name/img/image.jpg and <img> tag is in /app-name/src/app/my-component/my-component.component.html : 我在/app-name/img/image.jpg文件夹中有图像,并且<img>标记在/app-name/src/app/my-component/my-component.component.html

<img src="../../../img/image.jpg">

When i load page, i get error: GET http://localhost:4200/img/image.jpg 404 (Not Found) 当我加载页面时,出现错误:GET http:// localhost:4200 / img / image.jpg 404(未找到)

How to create url address in angular2? 如何在angular2中创建URL地址? The same problem is when i added script url in index.html. 同样的问题是当我在index.html中添加脚本URL时。

Thanks for advices. 感谢您的建议。

If you are using angular-cli to build your project. 如果您使用angular-cli来构建项目。

You need to include your img directory in the list of assets that needs to be copied to the output (deployable) directory. 您需要将img目录包括在需要复制到输出(可部署)目录的资产列表中。

In the .angular-cli.json file, add the img directory to the below array: .angular-cli.json文件中,将img目录添加到以下数组:

apps[0].assets

And then you can use like below 然后你可以像下面这样使用

<img src="img/image.jpg">

It would be something like 就像

"apps": [
{
  "root": "src",
  "outDir": "dist",
  "assets": [
    "assets",
    "img"
  ],

It seems like you did not include your img folder into your src folder, so try to put it there and adjust your src attribute value to /img/image.jpg 似乎您没有将img文件夹包含到src文件夹中,因此请尝试将其放在此处并将src属性值调整为/img/image.jpg

in general: make sure everything you want to use inside you application is in your src folder. 通常,请确保要在应用程序中使用的所有内容都在src文件夹中。 that content in there (and only that content) will then eventually be used to be processed(transpiled, bundled, minified and so on) and then end up in a webserver. 在那里的内容(只有该内容)最终将被用于处理(转译,捆绑,缩小等),然后最终存储在Web服务器中。

all other files outside of the src folder are for other purposes, like configuration files, node_modules, dist folders and so on src文件夹之外的所有其他文件都用于其他目的,例如配置文件,node_modules,dist文件夹等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM