0

When trying to show images from server : Template

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

Component (1) when i try this

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

It works fine (2) But when doing,

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

Doesn't work and Angular add a it's host and i get this error :

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

(3) even this way :

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

getting this error

src="http://SafeValue must use [property]=binding: http://localhost:400 .... (see http://g.co/ng/security#xss)
ketimaBU
  • 901
  • 4
  • 15
  • 35
  • 2
    What's the diffrence with your previous question? https://stackoverflow.com/questions/45720756/angular4-show-image-from-server – Vega Aug 16 '17 at 20:54

2 Answers2

2

In index.html set base href

<base href="/">

If your folder structure was something like this:

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

Then this would work:

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

ng serve essentially performs an ng build in memory so the assets configured in .angular-cli.json should be available.

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

Which also means that the output of ng build can be used to preview what is available via ng serve

JGFMK
  • 8,425
  • 4
  • 58
  • 92
1

You should use this in your Component :

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

or

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

(or with other bypassSecurityTrustUrl 's family functions to suit your needs)

You should not try to concatenate the result of the function (of type SafeUrl) with a string.

Pac0
  • 21,465
  • 8
  • 65
  • 74