我正在Angular中创建一个图像库。点击每个图像我想显示单独的组件,基本上是点击图像但是全尺寸。 Porblem是我不知道如何获得点击的图像。
到目前为止,我有这项服务来提出API请求来获取图片。
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class ImagesService {
constructor(private http: HttpClient) { }
images = [];
link = 'https://api.com?k=';
ApiKey = '12345';
public loadImages() {
return this.http.get(this.link + this.ApiKey);
}
}
然后我在Gallery Component中订阅了loadImages()
export class GalleryComponent {
visibleImages:Object = [];
constructor(private imagesService: ImagesService) {
this.imagesService.loadImages().subscribe(data => this.visibleImages = data);
}
}
然后在Gallery组件的HTML中,我显示这样的图像
<li *ngFor="let image of visibleImages">
<a [routerLink]="['/image', image.id]">
<img src="{{image.urls.small}}"/>
</a>
</li>
所以问题是如何获得点击图像?我在服务中想过这样的事情。但是这个问题是我如何将从API获得的数据存储到this.images
?另外,据我所知,我收到的回复是一个Observable,所以我无法真正将它存储到一个数组中?
getImage(id:number) {
this.images.slice(0).filter(image => image.id == id);
}
在图像组件
中ngOnInit() {
this.image = this.imagesService.getImage(+this.route.snapshot.params['id'])
}
答案 0 :(得分:1)
使用do
运算符拦截数据:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/do';
@Injectable()
export class ImagesService {
constructor(private http: HttpClient) { }
images = [];
link = 'https://api.unsplash.com/photos/?client_id=';
ApiKey = 'your key';
public loadImages() {
return this
.http.get(this.link + this.ApiKey)
.do((images: any[]) => this.images = images)
}
getImage(id:number) {
this.images.slice(0).filter(image => image.id == id);
}
}
如果ImageComponent与GalleryComponent位于同一页面,则必须订阅this.route.params
:
ngOnInit() {
this.route.params.subscribe(params => this.image = this.imagesService.getImage(+params['id']))
}