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:

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

Acquire XML documentation for overloaded functions in Typescript

Is it possible for an overloaded function in a subclass to automatically inherit the XML documentation from its base class? When hovering over myFunc I want to be able to see the documentation from the base class when I hover over myFunc, rather than ju ...

Cloud Formation from CDK doesn't pause for addDependency to finish

I'm currently in the process of building a CDK stack and I am fairly new to CDK. My goal is to create a Simple Email Service (SES) ConfigurationSet followed by an EmailIdentity. The issue I encountered is that the creation of the EmailIdentity fails d ...

Angular2: Retrieve and process a JSON array from an API

I'm currently facing an issue with my service while attempting to fetch a json array from an api and showcase it on the page. I believe there might be an error in my code, but I can't pinpoint exactly where. getAuctions(): Promise<Auction[ ...

Is there a way to incorporate the router into the observable within the guard?

Is there a way to inject a router into my guard when I have an Observable method returned? I want to implement routing with a redirect to the login page if a certain condition is met: If the result of the isAccessToLobby method is false, then redirect to t ...

What is the method for adding local images to FormData in Expo version 48 and above?

When working with Expo v47 and its corresponding React Native and TypeScript versions, FormData.append had the following typing: FormData.append(name: string, value: any): void An example of appending images using this code could be: const image = { uri ...

Launching in dynamically loaded modules with bootstrapping

The Angular Guide explains that during the bootstrapping process, components listed in the bootstrap array are created and inserted into the browser DOM. However, I have noticed that I am unable to bootstrap components in my lazy loaded feature modules. E ...

Angular HTTP event progress causing Bootstrap progress bar to not update automatically

I've been working on displaying the progress of my post request using HTTP Event and a bootstrap progress bar. The progress event is functioning correctly (I can see it in the console), but for some reason, the changes are not reflected in the progres ...

The parameter 'prev: todoType[] => todoType[]' cannot be assigned to the type 'todoType[]'.ts(2345)

An issue has arisen with this.props.update as mentioned in the title import { useState } from "react"; import axios from "axios"; import { todoType } from "../../types/todo"; type sendResponse = { task: string; }; type getRe ...

Utilizing Form Validation in Angular 4

In the process of developing a straightforward Angular application that utilizes Twitter Bootstrap and jQuery to showcase employee data. I have hardcoded 4 sets of data which are displayed in a table, as shown in the attached image. The addition of an "Add ...

Is the Angular Karma test failing to update the class properties with the method?

I am struggling to comprehend why my test is not passing. Snapshot of the Class: export class Viewer implements OnChanges { // ... selectedTimePeriod: number; timePeriods = [20, 30, 40]; constructor( /* ... */) { this.selectLa ...

Alerts created with the AlertController in Ionic 4 Angular are not displaying the message when the

After creating a reliable alert service for my Ionic 4 project, I encountered an issue when building the release version of the app. Despite functioning perfectly in other environments like "ionic serve" and "ionic cordova emulate", the message part of the ...

The inner panel height does not extend to 100% when there is overflow

When pressing the submit button on a panel containing components, an overlay appears but does not cover the entire parent panel if scrolled to the bottom. Additionally, I want the spinner to always be centered, whether scrolling or not. I've tried usi ...

Issue with NestedKeyof type arising from circularly referencing objects

Currently, I am in the process of constructing a library and my task involves implementing NestedKeyof. During my research, I came across the following code snippet: type NestedKeyOf<T extends object> = { [Key in keyof T & (string | number)]: ...

Troubleshooting issue in Angular 6 mat-select: original array not resetting after filtering values

When filtering an array based on multiple selections from a mat-select, everything works smoothly except for one issue - if I select an option and then deselect it, the entire array disappears from the UI. However, if I select a few other options after tha ...

Errors encountered when using TypeScript with destructured variables and props not being recognized

I have a function that returns data. The object is structured with properties such as headerMenu, page, content, and footer. These properties are defined in DataProps interface. When I try to destructure the data object using the line: const { headerMenu, ...

The Sourcemap is not correctly aligning with the expected line number

Currently working with the angular2-webpack-starter technology and utilizing VSCode along with Chrome debugger. After numerous attempts, I was able to successfully set a breakpoint, but it appears that the line mapping is incorrect. The issue persists in ...

Unveiling the magic: Dynamically displaying or concealing fields in Angular Reactive forms based on conditions

In my current scenario, there are three types of users: 1. Admin with 3 fields: email, firstname, lastname. 2. Employee with 4 fields: email, firstname, lastname, contact. 3. Front Office with 5 fields: email, firstname, lastname, airline details, vendo ...

Requesting access with Angular

Hi there, I'm currently getting started with Angular and I am eager to create a login feature. However, I am unsure of how to send a login request. Despite my efforts to find similar inquiries, the only information available pertains to older question ...

Unexpected token error in TypeScript: Syntax mistake spotted in code

Being new to Angular, I understand that mastering TypeScript is crucial for becoming a skilled Angular developer. Therefore, I created this simple program: function loge(messag){ console.log(messag); } var message:string; message = "Hi"; loge(messa ...

Unable to link to 'amount' because it is not a recognized attribute of 'ng-wrapper'

I recently made some changes to my code and now I'm encountering the error message "Can't bind to 'count' since it isn't a known property of 'ng-container'" Instead of having both the notification component and notificat ...