Angular 6 Failing To Load Images From Assets

2020-06-03 01:19发布

For some reason I can't get my images to show in my app. This is the error, tests and class:

The error: GET http://localhost:4200/assets/image.png 404 (Not Found)

<img class="logo" src="../../assets/image.png">
<img class="logo" src="../assets/image.png">
<img class="logo" src="assets/image.png">
//None of these work

.logo {
    height: 100px;
    width: auto;
    padding: 10px;
    display: block;
    margin: 0 auto;
}

Any idea why this is not working? My image.png is in my assets folder which is located at src/assets/image.png.

Update:

So we did a test. We copied all the node modules and the project files to another pc and there the images loaded correctly. So I assume the problem lies outside the angular project it self.

12条回答
smile是对你的礼貌
2楼-- · 2020-06-03 01:58

The folder which contains your assets (like pictures) needs to be declared in assets array inside your angular.json

Angular only recognizes those assets which have been declared in angular.json or the assets which come from web.

Additionally, from all the three options following will work for you:-

<img class="logo" src="assets/image.png">
查看更多
Explosion°爆炸
3楼-- · 2020-06-03 01:58

Try this:

<div class="logo"></div>

.logo {
    height: 100px;
    width: auto;
    padding: 10px;
    display: block;
    margin: 0 auto;
    background:url('assets/image.png') no-repeat center center;
}
查看更多
该账号已被封号
4楼-- · 2020-06-03 02:00
<img class="logo" src="assets/image.png">

This is the right path, probably something else went wrong.

check that the image name or if its jpeg. maybe you added a new folder in the assets folder ? , like images if so the code should look like this

<img class="logo" src="assets/image/image.png">
查看更多
欢心
5楼-- · 2020-06-03 02:15

Add assets folder to your angular.json.

"assets": [
    "src/assets"
 ],

Then refer the images like below,

<img src="/assets/image.png">

This should work.

查看更多
We Are One
6楼-- · 2020-06-03 02:17

I had the same problem as well. and for me was to add a '/' before the assests directory:

查看更多
叛逆
7楼-- · 2020-06-03 02:18

Try this <img class="logo" src="./assets/image.png">

also right click your picture and check if the extension is PNG instead of png, if so write image.PNG

查看更多
登录 后发表回答