如何在angular2中使用observable获取所有YouTube视频

时间:2016-06-22 07:17:17

标签: typescript youtube angular rxjs observable

我的问题是,我会从youtube频道获取所有视频,这是68个视频但youtube每个请求只允许50个视频。我知道pageToken,但我先得到最早的视频。

现在我的想法,我会得到所有nextPageTokens,然后从频道获取所有带有nextPageTokens的视频,并在获取后对它们进行排序。

import {Injectable, Inject} from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/scan';
import {Observable} from 'rxjs/Rx';

@Injectable()
export class YoutubeService {

videoArray:Array<any> = [];

constructor(@Inject(Http) private _http:Http) {

}

private extractData(res) {
let body = res.json();
return body || null;
}

private handleError(error:any) {
let errMsg = (error.message) ? error.message :
  error.status ? `${error.status} - ${error.statusText}` : 'Server    
error';
console.error(errMsg);
return Observable.throw(errMsg);
}


private fetchToken(token = '') {

return new Observable(observer => {

  let apiUrl = 'https://www.googleapis.com/youtube/v3/';
  let part = 'playlistItems?part=snippet';
  let playlistId = '&playlistId=PLBC4D1CE42B269BE5';
  let maxResults = '&maxResults=5';
  let nextPageToken = '&pageToken=' + token;
  let apiKey = '&key={APIKEY}';

  console.log(apiUrl + part + playlistId + maxResults + nextPageToken + apiKey);

  this._http.get(apiUrl + part + playlistId + maxResults + nextPageToken + apiKey)
    .map(this.extractData).subscribe(
    data => {
      this.videoArray.push(data.items);
      console.log(data.nextPageToken);
      if(data.nextPageToken !== undefined){
        this.fetchToken(data.nextPageToken).subscribe();
        observer.next(this.videoArray);
      } else {

      }
    });
})
}

public searchYouTube() {

this.fetchToken().subscribe(
  data => {
    console.log(data)
  }
)}}

有了这个,我得到了一个包含5个视频阵列的数组。是否可以更轻松,更清晰地获取数据。

最好的问候

1 个答案:

答案 0 :(得分:1)

您可以使用expand运算符捕获响应并将其反馈到源代码中:

function fetchToken(token) {
  if (typeof token = 'undefined')
    return Rx.Observable.empty();

  const baseUrl = 'https://www.googleapis.com/youtube/v3/';
  const playlistId = 'PLBC4D1CE42B269BE5';
  let url = `${baseUrl}/playlistItems?part=snippet&playlistId=${playlistId}&maxResults=5&pageToken=${token}&key=${API_KEY}`;

  return this._http.get(url).map(this.extractData);
}

//The initial request
fetchToken('')
   //Invokes subsequent results based on the result of this one
   //and feeds them back to this operator
   //1 indicates the number of active requests to allow (concurrency 1)
  .expand(data => fetchToken(data.nextPageToken), 1)
  //Extract the video items
  .pluck('items')
  //Update the playlist
  .subscribe(videos => this.videoArray.push(videos));