Angular4将其主机名添加到图像src

时间:2017-08-16 19:12:33

标签: angular

尝试从服务器显示图片时: 模板

<img [src]="file.url">

组件 (1)当我尝试这个时

  this.file.url="http://localhost:4000/uploads/results/101_5.png";

工作正常 (2)但是在做的时候,

 this.file.url=this.fromServer.url; // URl from server

不起作用,Angular添加它的主机,我收到此错误:

101_5.png:1 GET http://localhost:4000/uploads/results/101_5.png 404 (Not Found)

(3)即便如此:

this.file.url= "http://"+this.sanitizer.bypassSecurityTrustResourceUrl(this.fromServer.url);

收到此错误

src="http://SafeValue must use [property]=binding: http://localhost:400 .... (see http://g.co/ng/security#xss)

2 个答案:

答案 0 :(得分:2)

index.html 设置base href

<base href="/">

如果您的文件夹结构是这样的:

+src
 +app
 +assets
  +images
   logo-large.png

然后这会起作用:

<img src="assets/images/logo-large.png"/>

ng serve 基本上在内存中执行 ng build ,因此 .angular-cli.json 中配置的资产应该可用。

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

这也意味着 ng build 的输出可用于预览通过 ng serve

提供的内容

答案 1 :(得分:1)

你应该在你的组件中使用它:

menuModel

this.file.url = sanitizer.bypassSecurityTrustUrl(this.fromServer.url);

(或其他bypassSecurityTrustUrl的家庭功能,以满足您的需求)

您不应该尝试将函数(类型为SafeUrl)的结果与字符串连接起来。