简体   繁体   中英

Generate template based on an API id

As a complete beginner with Angular and APIs I've hit a wall and am not sure how to proceed. I'm currently trying to create a website like imdb with the help of the tmdb api https://www.themoviedb.org/documentation/api

I've managed to show ie a list of popular movies. But now what I'd like is that once a user clicks on a movie, based on the id it should generate a template and create content based on the movie id

<div *ngFor="let movie of movies$">
    <a routerLink="/movie/{{movie.id}}"> // <- this path should be generated
        <img src="https://image.tmdb.org/t/p/w200/{{movie.poster_path}}" >
    </a>
</div>

Like this: https://www.themoviedb.org/movie/299536-avengers-infinity-war How would I go about doing this?

The MovieDB API is going to give you the details about the movie if you pass the movie id. And each movie will have details like title, director, cast, poster image, etc. Given this case, create a common template using the details you get from the API and then just substitute the values in template placeholders. It's just as simple as that.

Movie component:

@Component({
  selector: 'my-movie',
  template: `
    <ng-container *ngIf="movie">
      <h1>{{ movie.name }}</h1>
      <p>Director: {{ movie.director }}</p>
      <p>Comics: {{ movie.comics }}</p>
    </ng-container>
  `
})
export class MovieComponent implements OnInit {
  movie: any;

  constructor(private movieService: MovieService, private route: ActivatedRoute) {}

  ngOnInit() {
    /**
     * Subscribes to route changes
     * If route params changes, get the movie id from URL
     * and get the info about the movie from IMDB API
     */
    this.route.params
      .pipe(
        map(params => +params['id']),
        switchMap(id => this.movieService.getInfo(id))
      )
      .subscribe(info => this.movie = info);
  }
}

You can find the complete example here in Stackblitz. I'm just using hard-coded data in MovieService file. Replace them with your API calls and everything should work as is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM