簡體   English   中英

根據 API id 生成模板

[英]Generate template based on an API id

作為一個完整的 Angular 和 API 初學者,我遇到了困難,不知道如何繼續。 我目前正在嘗試在 tmdb api https://www.themoviedb.org/documentation/api的幫助下創建一個類似 imdb 的網站

我設法顯示即流行電影的列表。 但現在我想要的是,一旦用戶點擊電影,它應該根據 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>

像這樣: https : //www.themoviedb.org/movie/299536-avengers-infinity-war我該怎么做?

如果您傳遞電影 ID,MovieDB API 將為您提供有關電影的詳細信息。 每部電影都有標題、導演、演員、海報圖像等詳細信息。在這種情況下,使用從 API 獲得的詳細信息創建一個通用模板,然后只需替換模板占位符中的值。 就這么簡單。

電影組件:

@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);
  }
}

你可以找到完整的例子這里在Stackblitz。 我只是在 MovieService 文件中使用硬編碼數據。 用您的 API 調用替換它們,一切都應該按原樣工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM