Search code examples
javascriptangularangular-httpclient

How to get img url from api which is key based in angular 5?


I'm using angular 5. I write bellow http.get method to get data from api in angular 5. I want to get the url of image to use this in my slider.

getImages(){
    this.httpclient.get('blabla/banner.php').subscribe((result) => {
    this.images = result;
    console.log(this.images);
})
}

but I'm getting data from api which id based below is my response

{  
   status:"success",
   …
}img:[  
   {  
      id:"1",
      banner:"/upload/img.jpg"
   },
   …
]0:{  
   id:"1",
   banner:"pload/img.jpg"
}1:{  
   id:"2",
   banner:"load/img2.jpg"
}2:{  
   id:"3",
   banner:"/admin/upload/img3.jpg"
}status:"success"

this my html template. I don't know is this right or wrong.

<div class="container">
    <div class="row">
        <div id="myCarousel" class="carousel slide" data-ride="carousel">
          <!-- Indicators -->
          <ol class="carousel-indicators">
            <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
            <li data-target="#myCarousel" data-slide-to="1"></li>
          <button ></button>
            <li   data-target="#myCarousel" data-slide-to="2"></li>
          </ol>
          <!-- Wrapper for slides -->
          <div class="carousel-inner">
            <div class="item active" *ngFor="let image of images">
              <img src="{{image.banner}}">
            </div>

         <!--    <div class="item">
              <img src="http://asianstylemagazine.com/wp-content/uploads/2016/04/housefull-1.jpg" alt="Chicago">
            </div>

            <div class="item">
              <img src="https://www.artsfon.com/large/201705/97685.jpg" alt="New York">
            </div>
          </div> -->

          <!-- Left and right controls -->
          <a class="left carousel-control" href="#myCarousel" data-slide="prev">
            <span class="glyphicon glyphicon-chevron-left"></span>
            <span class="sr-only">Previous</span>
          </a>
          <a class="right carousel-control" href="#myCarousel" data-slide="next">
            <span class="glyphicon glyphicon-chevron-right"></span>
            <span class="sr-only">Next</span>
          </a>
        </div>
    </div>
</div>

I'm getting this after using result.img enter image description here

I'm beginner to angular please help. Thank you.


Solution

  • You need to make sure you get the correct data

    getImages(){
        this.httpclient.get('blabla/banner.php').subscribe((result : any) => {
        this.images = result.img;
    })
    }
    

    Also, in your carrousel, you need to make sure that only one item is active at the beginning (for now, all items have the active class)

    <div class="item" [ngClass]="{'active': i==0}" *ngFor="let image of images; let i = index">