简体   繁体   English

根据 API id 生成模板

[英]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.作为一个完整的 Angular 和 API 初学者,我遇到了困难,不知道如何继续。 I'm currently trying to create a website like imdb with the help of the tmdb api https://www.themoviedb.org/documentation/api我目前正在尝试在 tmdb api https://www.themoviedb.org/documentation/api的帮助下创建一个类似 imdb 的网站

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但现在我想要的是,一旦用户点击电影,它应该根据 id 生成一个模板并根据电影 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?像这样: https : //www.themoviedb.org/movie/299536-avengers-infinity-war我该怎么做?

The MovieDB API is going to give you the details about the movie if you pass the movie id.如果您传递电影 ID,MovieDB API 将为您提供有关电影的详细信息。 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.每部电影都有标题、导演、演员、海报图像等详细信息。在这种情况下,使用从 API 获得的详细信息创建一个通用模板,然后只需替换模板占位符中的值。 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.你可以找到完整的例子这里在Stackblitz。 I'm just using hard-coded data in MovieService file.我只是在 MovieService 文件中使用硬编码数据。 Replace them with your API calls and everything should work as is.用您的 API 调用替换它们,一切都应该按原样工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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