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

Time:09-20

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?

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
      }
    ]
  }
];

CodePudding user response:

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

CodePudding user response:

The proper way how you can achieve desired values. Try this way.

export class MovieDetailsComponent implements OnInit {
  movie$!: Observable<Movie>;
enter 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);
      })
    );
  }
}

Ref Angular official doc: https://angular.io/guide/router-tutorial-toh#route-parameters-in-the-activatedroute-service

  • Related