What is the best way to access and utilize an id within an angular component's routing system?

I am currently working on an Angular application, and this is my first experience with JS. I have a main view where I display several elements, such as movies, each of which is clickable and links to a detailed view of the movie. My question is how can I handle the ID that I am passing to the detail view in my component's TypeScript file? I need this ID to fetch the corresponding movie object from the API.

Here is the code I have for the detail view:

export class MovieDetailComponent implements OnInit {
  public movie: MovieResponse[] = []

  constructor(private http: HttpClient,  private sanitizer: DomSanitizer) { }


  async ngOnInit(): Promise<void> {
    const movie = await firstValueFrom(this.http.get<[MovieResponse]>(environment.backend + '/api/v1/movie/' + this.route.snapshot.paramMap.get('id')));
    this.movie = await Promise.all(movie.map(async (movie) => {
      movie.cover_url = <string>this.sanitizer.bypassSecurityTrustResourceUrl(URL.createObjectURL(await firstValueFrom(this.http.get(movie.cover_url, {responseType: 'blob'}))));
      return movie;
    }));
  }
}

I am having trouble resolving

this.route.snapshot.paramMap.get('id')
. What do I need to do to work with the ID I am passing?

Here is the basic flow I am following:

  1. <div [routerLink]="['movie', movie.id]">
    -> links to the detail view
  2. In my app-routing.module.ts file, I have integrated the component for the detail view like this:
const routes: Routes = [
  {
    path: '',
    canActivate: [AuthGuard],
    children: [
      {
        path: '',
        component: MediaComponent
      },
      ... additional routes would be here.
      {
        path: 'movie/:id',
        component: MovieDetailComponent
      }
    ]
  }
];

Answer №1

import ActivatedRoute from '@angular/router'

To access the id parameter passed, add the following inside the component constructor:

public actRoute: ActivatedRoute 

Now, you can retrieve the id value by using a variable like this:

const id = this.actRoute.snapshot.params.id

Answer №2

Discover the correct method to achieve your desired results. Give this approach a try.

export class MovieDetailsComponent implements OnInit {
  movie$!: Observable<Movie>;
enter your code here
  constructor(
    private service: HeroService,
    private route: ActivatedRoute
  ) {}

  ngOnInit() {
    this.movie$ = this.route.paramMap.pipe(
      switchMap(params => {
        const id = params.get('id'));
        return this.service.getMovieDetails(id);
      })
    );
  }
}

Consult the Angular official documentation for more information: https://angular.io/guide/router-tutorial-toh#route-parameters-in-the-activatedroute-service

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

Tips on preventing image previews from consuming too much text data while updating a database in Angular 12 using Material UI for image uploads within a FormGroup object

Currently working with Angular 12 and Angular Material for image uploads with preview. I have a formgroup object below, but I'm running into issues with the 197kb image preview text being inserted into the database. Despite trying setValue/patchValue/ ...

Enhancing Angular HighChartsIs it time to rev

There seems to be an issue with the highchart not redrawing itself when dynamically changing plot options. I have integrated Highcharts into my code as shown below: In the HTML: <highcharts-chart [Highcharts]="Highcharts" [options]="opt ...

What if we had webpack disregard certain syntactic enhancements?

For instance: using optional chaining The application I'm working on is strictly for internal use, and it's specifically optimized for the latest Chrome browser. This means I can take advantage of syntactic sugar without needing to compile it, w ...

When dealing with errors arising from API calls, Angular can be prone to throwing error messages

I am currently creating an Angular service class to interact with APIs. However, I am facing an issue when handling Internal server errors in the response and need to send an error message to the user. The services are designed for retrieval but encounteri ...

Mistakes in combining Angular NgRx actions and union types

After reviewing my code, I have encountered the following issues: In my shared.actions.ts file: import { Action } from '@ngrx/store'; import { Error } from '../error.interface'; export const types = { IS_LOADING: '[SHARED] IS_L ...

Filtering without the includes() Method

I have two Objects that are structured as follows: export const recipes: Recipe[] = [ new Recipe( id: "Green", scenario: ["1", "2"]), new Recipe( id: "Blue", scenario: ["1", "2","2"]) ]; export const scenarios: Scenario[] = [ new Scenario( id: "1 ...

Exploring Angular 2 Routing across multiple components

I am facing a situation where I have an app component with defined routes and a <router-outlet></router-outlet> set. Additionally, I also have a menu component where I want to set the [routerLink] using the same routes as the app component. How ...

Executing cypress tests with tags in nrwl nx workspace: A simple guide

Currently, I am working within a nrwl nx workspace where I have set up a cypress BDD cucumber project. My goal is to run cypress tests based on tags using nrwl. In the past, I would typically use the "cypress-tags" command to achieve this. For example: &q ...

Adding a declaration file to a package that relies on an external declaration file can be achieved by following these

In the process of developing a library that relies on another package lacking a declaration file in its npm package, I have successfully installed the necessary declaration file with typings. Everything seems to be working well. Yet, the question remains: ...

Angular2 Event:keyup triggers the input to lose focus

I am working on a component with an input element that is bound to a property. I want the input field to update in real time as I type in it. Here is my current code: <input type="text" #updatetext [value]="item.name" (keyup)="updateItem(item.$key, up ...

Error: Angular version 5.1.0 is unable to set the header content-type to application/json for HttpClient

I have been attempting to customize the header for a POST API request to be of content type application.json. let options: { headers?: {'Content-Type':'application/json'} } Unfortunately, this customization is not being successfully a ...

Is it possible for TypeScript to automatically determine the specific type that was used in a union type parameter?

I need some help with a utility function I'm working on that can remove a specified number of elements from either a string or an array. My goal is to have the compiler determine whether the return value should be a string or an array based on what is ...

How can I simulate or manipulate the element's scrollHeight and clientHeight in testing scenarios?

In my JavaScript code, I have a function that checks if an HTML paragraph element, 'el', is a certain size by comparing its scrollHeight and clientHeight properties: function isOverflow(element: string): boolean { const el = document.getEleme ...

Warning: Typescript is unable to locate the specified module, which may result

When it comes to importing an Icon, the following code is what I am currently using: import Icon from "!svg-react-loader?name=Icon!../images/svg/item-thumbnail.svg" When working in Visual Studio Code 1.25.1, a warning from tslint appears: [ts] Cannot ...

Utilizing complex data with Angular 5 [Select+Option] - a comprehensive guide

I have a complex dataset stored in the app.component.ts file that looks like this: export class AppComponentimplements OnInit { tests = { 'name': 'Bob', 'grade': '5th', 'score' ...

Is it possible to enter NaN in Vue3?

Is there a way to handle NaN values and keep a field blank instead when calculating margins with a formula? https://i.stack.imgur.com/JvIRQ.png Template <form> <div class="row"> <div class="mb-3 col-sm ...

Are 'const' and 'let' interchangeable in Typescript?

Exploring AngularJS 2 and Typescript led me to create something using these technologies as a way to grasp the basics of Typescript. Through various sources, I delved into modules, Typescript concepts, with one particularly interesting topic discussing the ...

Overlapping Issue with Angular Bootstrap Dynamic Dropdown Menu

I'm currently working on creating a dynamic menu using Angular and Bootstrap for Angular. My main issue right now is that the submenus are overlapping each other when displayed on the page. To tackle this problem, I started off by referring to the ex ...

The select box is not displaying selected values in Angular 10, whereas it is displaying them in Angular 8 using the exact same

I am encountering an issue with the code provided below in two different applications developed using Angular 8 and 10. Strangely, it is not displaying the selected value in the Angular 10 app, while working perfectly fine in the Angular 8 app. <select ...

Altering or including new space variables within a custom Chakra-ui theme

Looking to customize spacing variables in a Chakra UI theme? I have successfully implemented various extensions, but changes to spacing are not being applied. const config: ThemeConfig = { initialColorMode: 'light', useSystemColorMode: false ...