使用 Angular HttpClient 映射 json

map json with AngularHttpClient

更新我的项目以使用 HttpClient 模块而不是 Http 模块后,以下不再有效。

问题是Property json does not exist on type object。我确实需要得到 items 属性。我怎样才能做到这一点?

private loadLatestVideosForChannelId( channelId: string ): Promise<any[]> {

    // load videos from youtube-data-api
    let videos = this.http.get( 
            'https://www.googleapis.com/youtube/v3/search' + 
            '?key=' + this.apiKey + 
            '&channelId=' + channelId + 
            '&part=snippet,id' + 
            '&order=date' + 
            '&type=video' +
            '&maxResults=3'
        )    
        .pipe(
            // if success
            map( res => {
                return res.json()['items'];    // the problem
            }),
            // if error
            catchError( (err) => {
                console.log( "YouTube API Error > Cannot get videos for this channel :(" )
                return null;
            }),
            take(1) 
        )
        .toPromise() as Promise<any[]>;

    return videos;
}

您不需要将 .json() 与 HttpClient 一起使用,因为响应本身已经是 json。改变如下,

  this.http.get( 
            'https://www.googleapis.com/youtube/v3/search' + 
            '?key=' + this.apiKey + 
            '&channelId=' + channelId + 
            '&part=snippet,id' + 
            '&order=date' + 
            '&type=video' +
            '&maxResults=3'
  )    
  .pipe(
    map((res: any) => {
      return res['items'];
    })
  )

;