map json with AngularHttpClient

末鹿安然 提交于 2019-12-20 06:13:30

问题


After updating my project to use the HttpClient module instead of the Http module, the following no longer works.

The problem is Property json does not exist on type object. I do need to get the items property. How can I achieve this?

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:


You don't need to use .json() with HttpClient as the response itself already a json. change it as follows,

  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'];
    })
  )

;



来源:https://stackoverflow.com/questions/54384961/map-json-with-angularhttpclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!