我试图将来自服务的图像推送到一个数组,并使用该数组尝试在Application中滑动图像。
import { Component, OnInit, Input } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
head_slider: any = [];
imgslider: any = [];
constructor( public http: HttpClient ) { }
slides = [ ];
slideConfig = {'slidesToShow': 4, 'slidesToScroll': 4};
ngOnInit() {
this.http.get('https://newsapi.org/v2/top-headlines?country=in&apiKey=69e4c9820959482e8c40e42f8bcfe975').subscribe(data => {
this.head_slider = data['articles'];
console.log(this.head_slider);
this.slides.push( 'img :' + this.head_slider.urlToImage);
});
}
addSlide() {
this.slides.push({img: 'http://placehold.it/350x150/777777'});
}
removeSlide() {
this.slides.length = this.slides.length - 1;
}
afterChange(e) {
console.log('afterChange');
}
}
在上面的代码中,我想将服务中存在的图像的键和值推送到数组 幻灯片= []; ,以这种方式--->幻灯片= [img:,img:,img:];
<ngx-slick class="carousel" #slickModal="slick-modal" [config]="slideConfig" (afterChange)="afterChange($event)">
<div ngxSlickItem *ngFor="let slide of slides" class="slide">
<img src="{{ slide.img }}" alt="" width="100%">
</div>
</ngx-slick>
<button (click)="addSlide()">Add</button>
<button (click)="removeSlide()">Remove</button>
<button (click)="slickModal.slickGoTo(2)">slickGoto 2</button>
<button (click)="slickModal.unslick()">unslick</button>
答案 0 :(得分:0)
请更改
this.slides.push( this.img = this.head_slider.urlToImage)
到
this.slides.push( {img: this.head_slider.urlToImage});
答案 1 :(得分:0)
您需要遍历head_slider
,因为它是一个数组。
ngOnInit() {
this.http.get('https://newsapi.org/v2/top-headlines?country=in&apiKey=<<api key here>>').subscribe(data => {
this.head_slider = data['articles'];
for(let i = 0; i < data['articles'].length; i++){
this.slides.push({img: data['articles'][i].urlToImage})
}
});
}