fetch list of artists
This commit is contained in:
@@ -1 +1,8 @@
|
||||
<p>artist-list works!</p>
|
||||
<ul>
|
||||
@for (artist of artists(); track artist.id) {
|
||||
<li>
|
||||
<h3>{{ artist.name }}</h3>
|
||||
</li>
|
||||
}
|
||||
</ul>
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { Component } from '@angular/core';
|
||||
import { Component, DestroyRef, inject, OnInit, signal } from '@angular/core';
|
||||
import { Artist } from '../artist.model';
|
||||
import { ArtistService } from '../artist.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-artist-list',
|
||||
@@ -6,6 +8,30 @@ import { Component } from '@angular/core';
|
||||
templateUrl: './artist-list.component.html',
|
||||
styleUrl: './artist-list.component.css'
|
||||
})
|
||||
export class ArtistListComponent {
|
||||
export class ArtistListComponent implements OnInit {
|
||||
artists = signal<Artist[] | undefined>(undefined);
|
||||
isFetching = signal(false);
|
||||
error = signal('');
|
||||
private artistService = inject(ArtistService);
|
||||
private destroyRef = inject(DestroyRef);
|
||||
|
||||
ngOnInit() {
|
||||
this.isFetching.set(true);
|
||||
const subscription = this.artistService.loadArtists().subscribe({
|
||||
next: (artists) => {
|
||||
this.artists.set(artists);
|
||||
},
|
||||
error: (error: Error) => {
|
||||
this.error.set(error.message);
|
||||
},
|
||||
complete: () => {
|
||||
this.isFetching.set(false);
|
||||
},
|
||||
});
|
||||
|
||||
this.destroyRef.onDestroy(() => {
|
||||
subscription.unsubscribe();
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
export interface Artist {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { inject, Injectable, signal } from "@angular/core";
|
||||
import { ErrorService } from "../../shared/error.service";
|
||||
import { HttpClient } from "@angular/common/http";
|
||||
import { Artist } from "./artist.model";
|
||||
import { catchError, map, throwError } from "rxjs";
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class ArtistService {
|
||||
private errorService = inject(ErrorService);
|
||||
private httpClient = inject(HttpClient);
|
||||
private artists = signal<Artist[]>([]);
|
||||
|
||||
loadedArtists = this.artists.asReadonly();
|
||||
|
||||
loadArtists() {
|
||||
return this.fetchArtists('http://127.0.0.1:8800/api/comics/artists', 'Someting went wrong fetching sports. Please try again later-');
|
||||
}
|
||||
|
||||
private fetchArtists(url: string, errorMessage: string) {
|
||||
return this.httpClient.get<Artist[]>(url).pipe(
|
||||
map((resData) => resData),
|
||||
catchError((error) => {
|
||||
console.log(error);
|
||||
return throwError(() => new Error(errorMessage));
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user