0

I'm making a gallery of images in Angular. On click on each image I want to display separate component which is basically clicked image but in full size. Porblem is I'm not sure how to get image which is clicked.

So far I have this service to make API request to get images.

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);
  }
}

Then I have Gallery Component where I subscribe to loadImages()

export class GalleryComponent {
   visibleImages:Object = [];

  constructor(private imagesService: ImagesService) {
    this.imagesService.loadImages().subscribe(data => this.visibleImages = data);
   }
}

Then in HTML of Gallery component I display images like this

<li *ngFor="let image of visibleImages">
  <a [routerLink]="['/image', image.id]">
    <img src="{{image.urls.small}}"/>
  </a>
</li>

So the problem is how to get clicked image? I thought about something like this in my service. But this problem that is how can I store data which I get from API to this.images? Plus as I understand the response which I'm getting back is an Observable so I can't really store it into an array?

getImage(id:number) {
    this.images.slice(0).filter(image => image.id == id);
  }

And in Image component

ngOnInit() {
    this.image = this.imagesService.getImage(+this.route.snapshot.params['id'])
  }
1
  • don't expose your api key Commented Dec 30, 2017 at 14:04

1 Answer 1

1

use do operator to intercept the data :

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);
  }
}

if the ImageComponent is in the same page as GalleryComponent you have to subscribe to the this.route.params :

ngOnInit() {
    this.route.params.subscribe(params  => this.image = this.imagesService.getImage(+params['id']))
  }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.