【问题标题】:How to find resource in relative path in Angular如何在Angular中的相对路径中查找资源
【发布时间】:2017-11-03 05:54:39
【问题描述】:

我的应用结构是这样的:

index.html
main.ts
app
 |--main.component.html
 |--main.component.ts
 |--app.module.ts
 |--note.png
... etc

我想使用同一文件夹下的 main.component.html 中的 note.png。 我试过<img src="note.png"/><img src="./note.png"/>,但是图片没有显示。 浏览器去/note.png搜索图片。

有没有使用相对路径定位资源的好方法?
我不能使用,因为我可能在不同的文件夹下有很多页面,它们的基本href不同。

【问题讨论】:

  • Angular 不同于普通的 html 结构。在普通的 html 中,如果我们访问 main.component.html,url 会像 /app/main.component.html。因此,如果我们在 html 中使用相对路径,它将转到 /app/note.png。但在 Angular 中,url 是 /index.html,但实际上会显示 main.component.html 的页面。有什么办法可以解决这个问题吗?
  • 你应该 ng-src
  • 告诉我我的回答能解决你的问题吗?
  • 非常感谢您的回复。 Angular中有ng-src吗?我没有使用 AngularJS。即使我可以使用 ng-src,那些风格的呢,比如:style="background-image: url(note.png); "
  • 我相信您需要将其保存在应用程序根级别的“资产”文件夹中。例如:“您的应用程序\src\assets\note.png”

标签: javascript html angular


【解决方案1】:

如果您使用的是 Angular CLI,您可以将资产放在您想要的任何文件夹中。您只需在此处将这些文件夹添加到您的 .angular-cli.json 文件中:

  "assets": [
    "assets",
    "favicon.ico"
  ],

因此,如果您想将某些图像放在 img 文件夹中,您可以像这样修改它:

  "assets": [
    "assets",
    "img",
    "favicon.ico"
  ],

希望对您有所帮助。

【讨论】:

  • 非常感谢,但是我想把我的图片和使用图片的ts和html放在同一个文件夹里。我不想创建一个asserts文件夹来存储所有页面的所有图片
  • 我相信你可以配置 webpack 从任何地方获取资产,但这太可怕了。只需使用资产并正确组织它。例如,每个组件 1 个文件夹。
猜你喜欢
  • 1970-01-01
  • 2010-12-08
  • 2011-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-10
相关资源
最近更新 更多