使用 AngularHttpClient 映射 json [英] map json with AngularHttpClient

查看:34
本文介绍了使用 AngularHttpClient 映射 json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

问题是属性json在类型对象上不存在.我确实需要获取 items 属性.我怎样才能做到这一点?

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;
}

推荐答案

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

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

;

这篇关于使用 AngularHttpClient 映射 json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆