Routing
{ path: 'albums/:id', component: AlbumSingleComponent },
Service
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class ApiService {
private readonly url = 'https://jsonplaceholder.typicode.com/albums';
private readonly albumUrl = 'https://jsonplaceholder.typicode.com/photos?albumId=';
constructor(private readonly http: HttpClient) {}
getAlbums$(): Observable<any[]> {
return this.http.get<any[]>(this.url);
}
getAlbum$(albumId: number): Observable<any> {
return this.http.get<any>(`${this.url}/${albumId}`);
}
getAlbumById$(albumId: number): Observable<any[]> {
return this.http.get<any[]>(`${this.albumUrl}${albumId}`);
}
}
Component
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ApiService } from 'src/app/services/api.service';
@Component({
selector: 'app-album-single',
templateUrl: './album-single.component.html',
styleUrls: ['./album-single.component.scss'],
})
export class AlbumSingleComponent implements OnInit {
id: number;
title: string;
photos: any = '';
constructor(private readonly route: ActivatedRoute, private readonly apiService: ApiService) {}
ngOnInit(): void {
//kinyeri az 'id' nevű paraméter értékét, és hozzárendeli azt a komponens id változójához.
this.route.params.subscribe((params) => {
this.id = params['id'];
});
// Az adott album lekérése az id alapján
this.apiService.getAlbum$(this.id).subscribe((album) => {
this.title = album.title;
});
// Az album képek lekérése az id alapján
this.apiService.getAlbumById$(this.id).subscribe((albumData) => {
this.photos = albumData;
});
}
}
Template
<section>
<div class="wrapper">
<h1>#{{ id }} - {{ title }}</h1>
</div>
</section>