How to serve up images in Angular2?

前端 未结 6 1907
遥遥无期
遥遥无期 2020-11-29 20:06

I am trying to put the relative path to one of my images in my assets folder in an image src tag in my Angular2 app. I set a variable in my component to \'fullImagePath\' an

相关标签:
6条回答
  • 2020-11-29 20:36

    Angular only points to src/assets folder, nothing else is public to access via url so you should use full path

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

    Or

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

    This will only work if the base href tag is set with /

    You can also add other folders for data in angular/cli. All you need to modify is angular-cli.json

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

    Note in edit : Dist command will try to find all attachments from assets so it is also important to keep the images and any files you want to access via url inside assets, like mock json data files should also be in assets.

    0 讨论(0)
  • 2020-11-29 20:40

    Just put your images in the assets folder refer them in your html pages or ts files with that link.

    0 讨论(0)
  • 2020-11-29 20:42

    If you do not like assets folder you can edit .angular-cli.json and add other folders you need.

      "assets": [
        "assets",
        "img",
        "favicon.ico"
      ]
    
    0 讨论(0)
  • 2020-11-29 20:50

    In angular only one page is requested from server, that is index.html. And index.html and assets folder are on same directory. while putting image in any component give src value like assets\image.png. This will work fine because browser will make request to server for that image and webpack will be able serve that image.

    0 讨论(0)
  • 2020-11-29 20:51

    Add your image path like fullPathname='assets/images/therealdealportfoliohero.jpg' in your constructor. It will work definitely.

    0 讨论(0)
  • 2020-11-29 20:53

    I am using the Asp.Net Core angular template project with an Angular 4 front end and webpack. I had to use '/dist/assets/images/' in front of the image name, and store the image in the assets/images directory in the dist directory. eg:

     <img  class="img-responsive" src="/dist/assets/images/UnitBadge.jpg">
    
    0 讨论(0)
提交回复
热议问题