【问题标题】:Display data from API call inside another API call在另一个 API 调用中显示来自 API 调用的数据
【发布时间】:2019-01-17 01:36:45
【问题描述】:

我正在尝试从 Youtube API 获取数据。我正在使用 2 个请求,一个用于视频列表,一个用于每个视频的详细信息。

我的第一个请求有效,我显示了 4 个带有缩略图、标题等的视频... 为了获取每个视频的更多信息,我在我的第一个 API 调用中尝试了一个 foreach 循环:

这是我的service.ts

    export class YoutubeDataService {

      constructor(private http: HttpClient) { }

      getList() {
         return this.http.get('https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCiRDO4sVx9dsyMm9F7eWMvw&order=date&maxResults=4&type=video&key={MY_KEY}')
      }

      getViews(id) {
         return this.http.get('https://www.googleapis.com/youtube/v3/videos?part=statistics&id=' + id + '&key={MY_KEY}');
      }
   }

这是我的 component.ts

    export class VideosComponent implements OnInit {

      videos: Object;
      items = [];
      views: Object;

      constructor(private youtube: YoutubeDataService) { }

      ngOnInit() {
         this.youtube.getList().subscribe(data => {
            this.videos = data.items;
            console.log(this.videos);
            this.videos.forEach(element => {
               this.youtube.getViews(element.id.videoId).subscribe(data2 => {
                  this.views = data2.items[0].statistics.viewCount;
                  console.log(this.views);
               });
            });
         });
      }

    }

还有我的component.html

    <div class="video col-xl-5" *ngFor="let video of videos.items">
       <a class="row" href="https://www.youtube.com/watch?v={{video.id.videoId}}">
          <img [src]="video.snippet.thumbnails.medium.url">
          <div class="col"> 
             <h3 class="titre">{{ video.snippet.title }}</h3>
             // Here I'd like to display infos I can only get from the second API call
             <p class="description">{{ video.snippet.description }}</p>
          </div> 
       </a>
    </div>

这里,代码按预期显示了标题、缩略图和描述,我的console.log(this.views);显示了每个视频的观看次数,但我找不到如何管理它。

更新

我知道我只需要将数据推送到数组中并在我的 html 中使用索引显示它: component.ts

    this.youtube.getList().subscribe(data => {
       this.videos = data.items;
       this.videos.forEach(element => {
          this.youtube.getViews(element.id.videoId).subscribe(data2 => {
             this.array.push(data2.items[0].statistics.viewCount);
          });
       });
    });

但我遇到了一个新问题:观看次数不是按视频排序的。每次我刷新页面时,它都会以不同的顺序显示 4 个观看次数。有没有办法解决这个问题?

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    您已经在运行您的第一个 HTTP 调用“getList”...您正在使用 forEach 迭代结果并获取视图计数...这一切都很好。

    当您调用第 2 次 HTTP 调用“getViews(id)”时,请确保将结果与 VideoId 的引用一起存储;这样你就可以简单地使用 *ngIf 在结果准备好时显示结果......

    HTML

    <div *ngFor="let video of videos">
      <p> ID# {{video.videoId}}: {{video.title}} "{{video.description}}"</p>
      <div *ngFor="let viewership of views">
        <span *ngIf="viewership.videoId == video.videoId"> number of views: {{viewership.viewCount}} </span>
      </div>
    </div>
    

    相关 TS:

    this.videos.forEach(element =>{
      this.views.push({ "videoId":element.videoId, "viewCount": this.getViews(element.videoId) });
    });
    

    对于工作演示,请参加look here - 学习愉快!!

    【讨论】:

    • 感谢您的帮助!我从您的代码中获得灵感,但我现在遇到了一个新问题,即 forEach 中的顺序。你能看看我更新的帖子吗?谢谢
    • 调用第二个函数的序列不是问题——序列在显示viewCount时出现;查看我的 HTML,其中 viewCount 数组显示在 views 数组中,并且仅在 videoId 相同时打印一个数字
    【解决方案2】:

    如果我理解您的意思,您是否想从第一个请求中获得响应并将其传递给第二个响应......如果您就是这个意思,那么您可以轻松地使用 request ...例如

    fetchRequest(){
    
      request(`FIRST_URL`,function (error, response, body){
    
      //error logging
      console.log('first request error:', error);
    
      var firstRes = JSON.parse(body)
    
         request(`SECOND_URL_WITH_FIRST_RES__${firstRes}`,function (error, response, body){
    
         //error logging
         console.log('Second request error:', error);
    
         var secondRes= JSON.parse(body)
    
         return secondRes
         }
      }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-19
      • 1970-01-01
      • 2018-08-17
      相关资源
      最近更新 更多