用AngularHttpClient映射json

时间:2019-01-27 04:03:50

标签: angular angular-httpclient

在将项目更新为使用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;
}

1 个答案:

答案 0 :(得分:1)

您不需要将.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'];
    })
  )

;