如何在 Angular2 中提供图像?

新手上路,请多包涵

我正在尝试将我的一个图像的相对路径放在我的资产文件夹中我的 Angular2 应用程序的图像 src 标记中。我在我的组件中将一个变量设置为“fullImagePath”并在我的模板中使用它。我尝试了许多不同的可能路径,但似乎无法提升我的形象。 Angular2 中是否有一些特殊路径总是相对于 Django 中的静态文件夹?

零件

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-hero',
  templateUrl: './hero.component.html',
  styleUrls: ['./hero.component.css']
})

export class HeroComponent implements OnInit {
  fullImagePath: string;

  constructor() {
    this.fullImagePath = '../../assets/images/therealdealportfoliohero.jpg'
  }

  ngOnInit() {
  }

}

我还将图片与该组件放在同一个文件夹中,因此由于同一文件夹中的模板和 css 可以正常工作,因此我不确定为什么图像的类似相对路径不起作用。这是与同一文件夹中的图像相同的组件。

 import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-hero',
  templateUrl: './hero.component.html',
  styleUrls: ['./hero.component.css']
})

export class HeroComponent implements OnInit {
  fullImagePath: string;

  constructor() {
    this.fullImagePath = './therealdealportfoliohero.jpg'
  }

  ngOnInit() {
  }

}

html

 <div class="row">
    <div class="col-xs-12">
        <img [src]="fullImagePath">
    </div>
</div>

应用树 \* 我省略了节点模块文件夹以节省空间

├── README.md
├── angular-cli.json
├── e2e
│   ├── app.e2e-spec.ts
│   ├── app.po.ts
│   └── tsconfig.json
├── karma.conf.js
├── package.json
├── protractor.conf.js
├── src
│   ├── app
│   │   ├── app.component.css
│   │   ├── app.component.html
│   │   ├── app.component.spec.ts
│   │   ├── app.component.ts
│   │   ├── app.module.ts
│   │   ├── hero
│   │   │   ├── hero.component.css
│   │   │   ├── hero.component.html
│   │   │   ├── hero.component.spec.ts
│   │   │   ├── hero.component.ts
│   │   │   └── portheropng.png
│   │   ├── index.ts
│   │   └── shared
│   │       └── index.ts
│   ├── assets
│   │   └── images
│   │       └── therealdealportfoliohero.jpg
│   ├── environments
│   │   ├── environment.dev.ts
│   │   ├── environment.prod.ts
│   │   └── environment.ts
│   ├── favicon.ico
│   ├── index.html
│   ├── main.ts
│   ├── polyfills.ts
│   ├── styles.css
│   ├── test.ts
│   ├── tsconfig.json
│   └── typings.d.ts
└── tslint.json

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

阅读 709
2 个回答

Angular 仅指向 src/assets 文件夹,没有其他内容可以通过 url 公开访问,因此您应该使用完整路径

 this.fullImagePath = '/assets/images/therealdealportfoliohero.jpg'

或者

 this.fullImagePath = 'assets/images/therealdealportfoliohero.jpg'

这仅在基本 href 标签设置为 /

您还可以在 angular/cli 中添加其他数据文件夹。您只需要修改 angular-cli.json

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

编辑中的注意事项:Dist 命令将尝试从资产中查找所有附件,因此将要通过 url 访问的图像和任何文件保留在资产中也很重要,例如模拟 json 数据文件也应该在资产中。

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

在 Angular 中,仅从服务器请求一页,即 index.html。 index.html 和 assets 文件夹位于同一目录中。在将图像放入任何组件时,会给出 src 值,例如 assets\image.png 。这将正常工作,因为浏览器将向服务器发出请求以获取该图像,并且 webpack 将能够提供该图像。

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

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