Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fetch/use an id im routing to in an angular component?

I’m wring an Angular application, this is also the very first time I’m in touch with JS, so I guess my question is very basic. I have a main view where I show many elemets, movies in this example, each element is clickable and referes to a detail view of the movie. My question now is how can I process the id I’m passing to the detail view at my components ts file? As in the end I need this ID to fetch my API for the actual movie object?!

This is my current 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;
    }));
  }
}

For some reason I dont get this to resolve: this.route.snapshot.paramMap.get('id').
Whats need to be done here to work with the id I pass?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Basically the flow im following:

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

>Solution :

import ActivatedRoute from '@angular/router'

Inside the component constructor, write this:

public actRoute: ActivatedRoute 

Then, you can have access to the id you passed with a variable
Say:

const id = this.actRoute.snapshot.params.id
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading