Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular path to image in assets on web server

Tags:

angular

I am new to Angular. I created a small web application with 2 images. The images are in myapp/src/assets/img1.jpg. On my local machine, everything works fine. When I call locasthost:4200 I can see the images, but when I upload the content of the dist folder (created with ng build --prod) to my web server, the images cannot be found.

my web server: abc.host.com/~user1/myapp

Parts (myapp) of the path are cut off. e.g. abc.host.com/~user1/assets/img1.jpg.

What <base href=""> should I use? What img src path to use so that images are shown on web server too? the following did not work:

<img src="/assets/img/img1.jpg" alt="/assets/img/img1.jpg">
<img src="../assets/img/img1.jpg" alt="../assets/img/img1.jpg">

I would like to keep everything relative.

SOLUTION:

  1. use <base href="./"> in your index.html
  2. <img src="assets/img/img1.jpg" alt="assets/img/img1.jpg">

My web server will now get the img from: abc.host.com/~user1/myapp/assets/img/img1.jpg

like image 540
Gero Avatar asked Jan 28 '23 01:01

Gero


1 Answers

It all depends on the base href you are providing in the index.html. All the images should be kept under 'assets' folder. And the path for any image in the project must be relative starting from this folder ie.

src="assets/img/img1.jpg"

As doing this, will remove the difficulty of file not found, which will arise in the deployment of the application.

Now, these steps will do the rest.

  • ng build --prod --base-href   /myApp - this command will add the base-href='/myApp' to index.html
  • Create folder myApp in the server's deployment folder, say in case of tomcat make this folder in webapps.
  • Copy the contents of dist folder to this myApp folder.
  • Run the server.

Application will be accessible at http://localhost:8080/my_app

If you dont want the context 'myApp' for your application, then try doing base href='./'

This helped in my case. Hope, it helps.

like image 122
Abhishek Kumar Avatar answered Jan 30 '23 14:01

Abhishek Kumar