角度,未找到图像(GET 404)

新手上路,请多包涵

我目前正在尝试将图像嵌入到我的角度项目中,但出现无法找到图像的错误。

 GET http://localhost:4200/logo.svg 404 (Not Found)

我试过像这样用标准方法嵌入图像

<img src="../logo.svg">

我检查了来源并尝试了其他文件格式。

原文由 Leonzen 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 423
2 个回答

@Parth Ghiya 评论了我的问题的答案。我不得不将图像放到 /src/assets 文件夹中。 Angular 现在可以找到图像了。

原文由 Leonzen 发布,翻译遵循 CC BY-SA 3.0 许可协议

应将静态资源(图像、字体、json 文件…等)添加到 assets 文件夹中。默认情况下,无论你放在资产文件夹中什么,你都可以直接从浏览器访问它并通过 HTTP 请求查询:

 📦src
 ┣ 📂app
 ┃ ┣ 📂core
 ┃ ┣ 📂shared
 ┃ ┣ 📜app-routing.module.ts
 ┃ ┣ 📜app.component.ts
 ┃ ┣ 📜app.module.ts
 ┣ 📂assets
 ┃ ┣ 📂img
 ┃ ┃ ┗ 📜logo.png // this will be served
 ┣ 📂static
 ┃ ┃ ┗ 📜background.png // this won't be served unless you add it to the assets array
 ┣ 📂environments
 ┣ 📂styles
 ┣ 📜favicon.ico
 ┣ 📜index.html
 ┣ 📜main.ts
 ┣ 📜polyfills.ts

现在,如果你想使用 logo.png 图像,即 assets/img 文件夹,你可以这样做:

 <img src="assets/img/logo.png" alt="logo">   <!-- OK  :)   ->
<img src="static/background.png" alt="logo"> <!-- Not OK :(->

if you want to use the background.png that is inside the static folder, you need to include the static folder in the assets array inside the angular.json 文件:

 ...
"assets": [
   "src/favicon.ico",
   "src/assets",
   "src/static"
],
...

 <img src="assets/img/logo.png" alt="logo">   <!-- OK :) ->
<img src="static/background.png" alt="logo"> <!-- OK :) ->

我想强调最好不要:

  • 使用 src/ 引用您的静态资源(图像等)。
  • 使用相对路径 ../logo.png

原文由 Benzara Tahar 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题