Currently, I am delving into Angular and exploring various basic concepts such as routing, Observables (and subscribing to them), making HTTP requests, and utilizing routing parameters. One scenario I have set up involves sending a HTTP GET request to JSONPlaceholder to retrieve all albums. To achieve this, I have created a service and added the following code snippet:
<a [routerLink]="['albums', album.id]">{{album.title}}</a>
This code is responsible for linking each album title to its respective detail view when clicked. For a more detailed look at my implementation, you can refer to the StackBlitz. Here's an overview of the relevant parts of my code:
album-detail.component.ts
import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AlbumService } from './albums.service';
import { IAlbum } from './album';
@Component({
template: './album-detail.component.html'
})
export class AlbumDetailComponent {
album: IAlbum;
constructor(private _route: ActivatedRoute, private _albumService: AlbumService) {}
ngOnInit(): void {
const id=+this._route.snapshot.paramMap.get('id');
console.log("called for: "+id);
this.getAlbumById(id);
}
getAlbumById(id: number) {
this._albumService.getAlbumById(id).subscribe({
next: album => this.onAlbumRetrieved(album)
})
}
onAlbumRetrieved(album: IAlbum): void {
this.album = album;
}
}
album.module.ts
import { NgModule } from '@angular/core';
import { AlbumListComponent } from './albums-list.component';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule } from '@angular/router';
import { HttpClientModule } from '@angular/common/http';
import { AlbumDetailComponent } from './album-detail.component';
@NgModule({
imports: [
BrowserModule,
HttpClientModule,
RouterModule.forChild([
{path: 'albums', component: AlbumListComponent},
{path: 'albums/:id', component: AlbumDetailComponent},
])
],
declarations: [
AlbumListComponent,
AlbumDetailComponent
]
})
export class AlbumModule { }
Although my HTTP GET request is successful, it seems like there is a glitch with my routing configuration: