A guide on successfully sending parameters to Angular routes

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:

https://i.sstatic.net/nkRK2.png

Answer №1

The routes for albums are not properly registered in your AppModule. Simply importing AlbumModule does not register the routes that are needed.

To handle the album routes, you can take one of two approaches:

  1. Delegate responsibility for the album routing by lazy loading the module.
  2. Register the album routing directly in your app module.

Lazily loading the module may be excessive for this situation, so it is recommended to move the routes from AlbumModule to AppModule:

RouterModule.forRoot([
  {path: 'home', component: HomeComponent},
  {path: 'albums', component: AlbumListComponent},
  {path: 'albums/:id', component: AlbumDetailComponent},
  {path: '', redirectTo: 'home', pathMatch: 'full'},
])

When creating router links, ensure they are absolute (rather than relative) by adding a slash before the route:

<a [routerLink]="['/albums', album.id]">{{album.title}}</a>

DEMO: https://stackblitz.com/edit/angular-dyq5wb

Additionally, make sure to update AlbumDetailComponent reference path:

templateUrl: './album-detail.component.html'
.

Answer №2

Two modifications are required:

Update the album-detail.component.ts file:

templateUrl: './album-detail.component.html'

Edit the album-list.component.html file:

<a [routerLink]="[album.id]">{{album.title}}</a>

Answer №3

Make the following changes only.

In album.module.ts

 RouterModule.forChild([
    {path: 'albums', component: AlbumListComponent},
    {path: 'albums/album/:id', component: AlbumDetailComponent},
 ])

In album-detail.component.ts

@Component({
  templateUrl: './album-detail.component.html'
})

Review the updated code in these two files.

In 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/album/:id', component: AlbumDetailComponent},
    ])
  ],
  declarations: [ 
    AlbumListComponent,
    AlbumDetailComponent
  ]
})
export class AlbumModule { }

In album-detail.component.ts

import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AlbumService } from './albums.service';
import { IAlbum } from './album';

@Component({
  templateUrl: './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;
  }
}

Feel free to reach out if you have any questions or concerns.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing dynamic secret key rotation for each environment during deployment with Angular, Jenkins, and Azure

My setup consists of multiple environments (development, testing, and production) where I utilize various 3rd-party services. Each environment requires different access tokens and secret keys for these services. For my CI/CD processes, I rely on Jenkins, ...

Choose an option from a selection and showcase it

I need to implement a modal that displays a list of different sounds for the user to choose from. Once they select a sound, it should be displayed on the main page. Here is the code snippet for the modal page: <ion-content text-center> <ion-ca ...

The type does not have a property named 'defaultProps'

I have a Typescript React class component structured like this: import React, { Component } from 'react'; interface Props { bar?: boolean; } const defaultProps: Partial<Props> = { bar: false, }; class Foo extends Component<Props& ...

simulate the behavior of a promise function within a class

I'm facing an issue with this class structure: @Injectable() class ServiceOne { method1(): Promise<any>{ return new Promise((resolve,reject)=>{ // performing some operations let value = 1; resolve({'value':1}); }); } ...

What steps are required to utilize NgbSortableHeader for sorting a bootstrap table through programming?

I have a bootstrap HTML table (operated by ng-bootstrap for Angular and utilized NgbdSortableHeader to arrange table columns by clicking on the column). When I click on an element, it sorts the column in ascending, descending, or ''(none) order. ...

Angular directive utilizing model reference for improved functionality

In my Angular 15 project, I am facing an issue with obtaining a reference to the ngModel in a custom directive. The goal is to create a directive that trims the input value before validation and triggers a data changed event to update the model. While I ca ...

Tips for creating a Bitbucket pipeline to deploy an Angular Universal application

I'm currently working on deploying my Angular universal app on a server using Bitbucket pipelines. The scripts I've written in bitbucket-pipelines.yml are as follows: pipelines: default: - step: name: Build app caches: ...

Showing an in-depth ngFor post on the screen

I am in the process of building a Blog with Angular 7, MongoDB, and NodeJS. Currently, I have developed a component that iterates through all the posts stored in the database and showcases them on a single page. <div class="container-fluid"> < ...

Experiencing the issue of receiving unexpected commas following a div

Here is the code written in TypeScript for creating an HTML table that displays items from nested objects. The code is functional, but there seems to be an issue with extra commas being printed which are not part of any specific line being executed. im ...

Using PrimeNG checkboxes to bind objects in a datatable

PrimeFaces Checkbox In the code snippet below, my goal is to add objects to an array named selectedComponents in a model-driven form when checkboxes are checked. The object type of item1 is CampaignProductModel, which belongs to an array called selectedC ...

What is the process for being directed to the identity server login within an Angular application?

Immediately redirecting users to the identity server upon accessing the application is my goal. Currently, there is a login button that directs users to the ID server with a click, but I want to eliminate this button and have the redirection occur automati ...

What steps can I take to resolve the problem of my NativeScript app not running on android?

When I entered "tns run android" in the terminal, the default emulator API23 launched but my app didn't install. Instead, an error occurred. This is different from when I run it on the IOS simulator, which runs smoothly without any errors. The nati ...

Preventing unauthorized users from accessing routes and child components in Angular 2

Here is the project structure: AppComponent Nav Component LoginComponent Once the user successfully authenticates through the form connected to Firebase, they are directed to the section accessible only by logged-in users. AccountComponent Profile ...

Awaitable HttpResponseError

My challenge is that I'm attempting to handle a HttpError or HttpErrorResponse using an observable. However, the only option I have is to handle the HttpResponse, which is necessary but not sufficient. I also need to find a way to avoid this limitatio ...

A Promise signature allows for the compilation of function bodies that return undefined

The compiler error that I expected to see when using this function does not actually occur. The function body is capable of returning undefined, yet the type signature does not mention this possibility. async function chat(_: at.ChatLine): Promise<Arr ...

What is the best way to modify the class of specific items within an ngFor loop in

I apologize if this question has already been addressed, but I couldn't find a suitable solution. My goal is to develop a basic chat application where messages sent by the current user are displayed on the right side of the screen, while messages from ...

Encountering incorrect month while utilizing the new Date() object

My Objective: I am looking to instantiate a new Date object. Snippet of My Code: checkDates (currentRecSec: RecommendedSection){ var currActiveFrom = new Date(currentRecSec.activeFrom.year,currentRecSec.activeFrom.month,currentRecSec.activeFrom.day ...

Generate a list of items in typescript, and then import them into a react component dynamically

I have a variable that stores key/value pairs of names and components in a TypeScript file. // icons.tsx import { BirdIcon, CatIcon } from 'components/Icons'; interface IconMap { [key: string]: string | undefined; } export const Icons: IconM ...

Unable to verify Angular 5 identity

After authentication, the application should redirect to another page. However, despite successful authentication according to the logs, the redirection does not occur. What could be causing this issue? auth.guard.ts: import { Injectable } from &apos ...

We're sorry, the request was blocked due to a missing Access-Control-Allow-Origin header

Recently, while working on a blog application with the front end in react + typescript and backend in go iris, I encountered an issue when trying to fetch blog content using a get request. The backend was running on localhost:5000 and the node at localhost ...