Lab 6: Services
Objectives
- Use a service to get static data
Instructions
Step 1: Create a service to get static data
- First, our album class need an id. So let's add an id to the album interface.
export interface Album {
id: number;
...
}
- Adapt your components so all albums have an ID. Make sure your app still compile
- For now, we will use a service to get static data. We will create a service that will return a list of albums.
- We also need to be able to have all crud operations on the albums.
- So let's create a service
AlbumStaticthat will return a list of albums and that will have the following methods:getAll(): returns all albumsget(id: number): returns the album with the given idadd(album: Album): adds a new albumupdate(album: Album): updates an albumdelete(id: number): deletes an album
private albums: Album[] = [/*Contains some albums*/]
getAll(): Album[] {
return this.albums;
}
update(album: Album) {
const index = this.albums.findIndex(a => a.id === album.id);
this.albums[index] = album;
}
// We are returning undefined if the album is not found, this come from the fact that we are using the find method
get(id: number): Album | undefined {
return this.albums.find(album => album.id === id);
}
// Some more methods...
[HINT] To delete an element from an array, you can use the
splicemethod.
Step 2: Use the service in the all the concerned components
album-list.component.ts:
- Inject the service
- Replace the albums array by an empty array and call the service in the constructor to get the albums.
albumsService = inject(AlbumStaticService)
albums: Album[] = [];
constructor() {
this.albums = this.albumService.getAll();
}
album-of-the-day.component.ts:
- Here we have two approaches we can use to get a random album:
- We can get all the albums and then get a random one from the array
- We can create a method in the service that will return a random album
- Let's use the second approach.
- In the service, create a method called
getRandomAlbum(): Albumthat will return a random album.
- In the service, create a method called
getRandomAlbum(): Album {
const index = Math.floor(Math.random() * this.albums.length);
return this.albums[index];
}
- We don't need then to have two variables in the
album-of-the-day.component.tsfile, we can just call the service to get the random album:- When the component load (use the constructor)
- When the user clicks on the button to get another random album
export class AlbumOfTheDayComponent {
albumService = inject(AlbumStaticService)
@Output() notifyParentToClose = new EventEmitter<boolean>();
albumOfTheDay: Album
constructor() {
this.changeAlbumOfTheDay()
}
changeAlbumOfTheDay() {
this.albumOfTheDay = this.albumService.getRandomAlbum()
}
closeAlbumOfTheDay() {
this.notifyParentToClose.emit(true);
}
}