从父级到服务的共享API数据

huangapple go评论89阅读模式
英文:

Sharing API data from parent to service

问题

我正在构建一个网站,显示排名前20的科幻电影。主页组件使用通过服务进行GET请求,以获取包含电影数据的对象数组。这些电影数据使用ngFor*在HTML模板中进行渲染。

每个电影缩略图都有一个点击处理程序,用于跳转到不同的页面,该页面将显示有关所选电影的更多信息,例如描述、评分等。对于这个第二个页面,我正在使用一个服务进行另一个GET请求,其中查询包含所选电影的ID作为参数。

渲染初始API电影数据的主页组件:

  1. import { Component } from '@angular/core';
  2. import { MovieDataService } from '../services/movie-data.service';
  3. @Component({
  4. selector: 'home-card',
  5. templateUrl: './home-card.component.html',
  6. styleUrls: ['./home-card.component.css']
  7. })
  8. export class HomeCardComponent {
  9. movieData: any = {};
  10. constructor(private movieDataService: MovieDataService) {}
  11. ngOnInit(): void {
  12. this.movieDataService.getData().subscribe((data) => {
  13. this.movieData = data;
  14. // JSON to console
  15. console.warn(data);
  16. })
  17. }
  18. }

主页的服务:

  1. import { HttpClient } from '@angular/common/http';
  2. import { Injectable } from '@angular/core';
  3. @Injectable({
  4. providedIn: 'root'
  5. })
  6. export class MovieDataService {
  7. constructor(private http: HttpClient) {}
  8. getData() {
  9. return this.http.get('https://api.themoviedb.org/3/discover/movie?api_key=9279f87c4b7f1cb1474b6d7cd6958a6d&language=en-US&with_genres=878');
  10. }
  11. }

将渲染所选电影数据的单个电影页面:

  1. import { Component, Input, Output, EventEmitter } from '@angular/core';
  2. import { DataService } from '../services/data.service';
  3. @Component({
  4. selector: 'info-page',
  5. templateUrl: './info-page.component.html',
  6. styleUrls: './info-page.component.css'
  7. })
  8. export class InfoPageComponent {
  9. singleMovieData: any = {};
  10. constructor(private DataService: DataService) {}
  11. ngOnInit(): void {
  12. this.DataService.getMovie().subscribe((data) => {
  13. this.singleMovieData = data;
  14. console.warn(data);
  15. })
  16. }
  17. }

单个电影页面的服务:

  1. import { Injectable } from '@angular/core';
  2. import { HttpClient } from '@angular/common/http';
  3. @Injectable({
  4. providedIn: 'root'
  5. })
  6. export class DataService {
  7. constructor(private http: HttpClient) { }
  8. movieId = 505642;
  9. getMovie() {
  10. return this.http.get(`https://api.themoviedb.org/3/movie/${this.movieId}?api_key=9279f87c4b7f1cb1474b6d7cd6958a6d&language=en-US`)
  11. }
  12. }

目前,我只能在查询中硬编码电影ID,这个方法有效。我还是Angular的新手,正在尝试找到一种动态获取所选电影ID并与服务共享,然后将其作为查询参数之一进行GET请求的方法。

英文:

I am building a website that shows the top 20 rated Sci-fi movies. The homepage component uses a GET request via a service to get an array of objects containing the moviesdata. This movie data is rendered usingngFor*` in its HTML template.

Each movie thumbnail has a click handler that routes to a different page that will display more information about that selected movie - i.e. description, ratings etc. For this second page, I am using a service that makes another GET request, where the query contains the selected movie's id as a parameter.

Homepage component that renders initial API movie data:

  1. import { Component } from '@angular/core';
  2. import { MovieDataService } from '../services/movie-data.service';
  3. @Component({
  4. selector: 'home-card',
  5. templateUrl: './home-card.component.html',
  6. styleUrls: ['./home-card.component.css']
  7. })
  8. export class HomeCardComponent {
  9. movieData: any = {};
  10. constructor(private movieDataService: MovieDataService) {}
  11. ngOnInit(): void {
  12. this.movieDataService.getData().subscribe((data) => {
  13. this.movieData = data;
  14. // JSON to console
  15. console.warn(data);
  16. })
  17. }
  18. }`

Service for the homepage

  1. import { HttpClient } from '@angular/common/http';
  2. import { Injectable } from '@angular/core';
  3. @Injectable({
  4. providedIn: 'root'
  5. })
  6. export class MovieDataService {
  7. constructor(private http: HttpClient) { }
  8. getData() {
  9. return this.http.get('https://api.themoviedb.org/3/discover/movie? api_key=9279f87c4b7f1cb1474b6d7cd6958a6d&language=en-US&with_genres=878');
  10. }
  11. }`

Single Movie page that will render the selected movie's data

  1. import { Component, Input, Output, EventEmitter } from '@angular/core';
  2. import { DataService } from '../services/data.service';
  3. @Component({
  4. selector: 'info-page',
  5. templateUrl: './info-page.component.html',
  6. styleUrls: ['./info-page.component.css']
  7. })
  8. export class InfoPageComponent {
  9. singleMovieData: any = {} ;
  10. constructor(private DataService: DataService) {}
  11. ngOnInit(): void {
  12. this.DataService.getMovie().subscribe((data) => {
  13. this.singleMovieData = data;
  14. console.warn(data);
  15. })
  16. }
  17. }`

Service for the Single Movie page

  1. import { Injectable } from '@angular/core';
  2. import { HttpClient } from '@angular/common/http';
  3. @Injectable({
  4. providedIn: 'root'
  5. })
  6. export class DataService {
  7. constructor(private http: HttpClient) { }
  8. movieId = 505642;
  9. getMovie() {
  10. return this.http.get(`https://api.themoviedb.org/3/movie/${this.movieId}? api_key=9279f87c4b7f1cb1474b6d7cd6958a6d&language=en-US`)
  11. }
  12. }

For now, I have only been able to hard code a movieId into the query, which works. I am still very new to angular, and I am trying to find a way to dynamically get the selected movie's id once it has been clicked, share it with the service, and make a GET request with that ID as one of the query's parameters.

答案1

得分: 1

需要将movieId传递给每个InfoPageComponent(如果我没记错的话,它是子组件)。

home-card.component.html

  1. <div *ngFor="let movie of movies;">
  2. <info-page [movieId]="movie.movieId"></info-page>
  3. </div>

info-page.component.ts

  1. export class InfoPageComponent {
  2. @Input()
  3. movieId: number;
  4. // 其他代码...
  5. getMovie() {
  6. this.dataService.getMovie(this.movieId).subscribe(...);
  7. }
  8. }

这是你要的翻译部分。

英文:

You need to pass movieId to your each InfoPageComponent (which is child component, if I am not wrong)

home-card.component.html

  1. &lt;div *ngFor=&quot;let movie of movies;&quot;&gt;
  2. &lt;info-page [movieId]=&quot;movie.movieId&quot;&gt;&lt;/info-page&gt;
  3. &lt;/div&gt;

info-page.component.ts

  1. export class InfoPageComponent {
  2. @input()
  3. movieId: number;
  4. ....
  5. getMovie() {
  6. this.dataService.getMovie(this.movieId).subscribe(...);
  7. }
  8. }

答案2

得分: 0

以下是翻译好的部分:

  1. info-page.service.ts
  2. public getMovie(movieId: number): IMovie {
  3. return this.http.get(`https://api.themoviedb.org/3/movie/${movieId}?api_key=9279f87c4b7f1cb1474b6d7cd6958a6d&amp;language=en-US`)
  4. }
英文:

Along with paranaaan's answer,

info-page.service.ts

  1. public getMovie(movieId: number): IMovie {
  2. return this.http.get(`https://api.themoviedb.org/3/movie/${movieId}?api_key=9279f87c4b7f1cb1474b6d7cd6958a6d&amp;language=en-US`)
  3. }

答案3

得分: 0

  • 定义路由为

{ path: 'movieInfo/:id', component: InfoPageComponent }

  • 导航至路由

<a [routerLink]="['/movieInfo', movie.id]">{{movie.name}} </a>

  • 在 InfoPageComponent 中获取路由参数

this.id = this._Activatedroute.snapshot.paramMap.get("id");

英文:
  • Define route as

{ path: 'movieInfo/:id', component: InfoPageComponent }

  • Navigate to the route

<a [routerLink]="['/movieInfo', movie.id]">{{movie.name}} </a>

  • get route parameter in InfoPageComponent

this.id=this._Activatedroute.snapshot.paramMap.get("id");

huangapple
  • 本文由 发表于 2023年2月16日 12:30:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75467878.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定