Search code examples
angularowl-carousel

angular owl carousel not working with http data


i'm getting data through http get. Afterwards i iterate over my images and add it inside an image array. If i declare my array directly with image url's its working fine but if i get my data async it showing this way: this is the right way

and here is how it looks like with my http get: wrong one

Here is my code:

  images = [];
 loadRestaurantInfos() {
this.acivatedRoute.paramMap.subscribe(params => {
  const url = `http://localhost:5000/location/searchnameonly?searchstring=${params.get('id')}`
  const data = this.http.get<any>(url, {
    headers: {token: this.apikey},
  });
  data.subscribe(datavalue => {
    this.images = [];
    if(datavalue.length>0){
      this.dataset = datavalue[0];
     this.setUpImageGallery(this.dataset.images);

    }else{
      this.router.navigate(['locations'])
    }
  })
 });

}

  setUpImageGallery(imagedata) {
  imagedata.forEach(element => {
    this.images.push(element);
  });

}

and here is my html:

    <owl-carousel
  [options]="{
    lazyLoad:true,
    responsive:{
'320':{
    items:1,
    autoplay:true,
    loop: true

},
'600':{
    items:1.5,
     autoplay:true,
    loop: false

},
 '980':{
    items:2,
    autoplay:true,
    loop: false
},
'1025':{
  items: 3,
  autoplay:true,
  loop: false
}}}">
<div *ngFor="let image of images" class="item">
  <img src="{{image}}">
</div>

</owl-carousel>

Solution

  • use ViewChild to refresh owl

    in html

    <owl-carousel #owlElement
    

    in component

    import {OwlCarousel} from 'ngx-owl-carousel';
    
    @ViewChild('owlElement') owlElement: OwlCarousel
    

    in your function

    setUpImageGallery(imagedata) {
      imagedata.forEach(element => {
        this.images.push(element);
      });
      this.owlElement.refresh()
    }