【问题标题】:map json with AngularHttpClient使用 Angular HttpClient 映射 json
【发布时间】:2019-01-27 12:07:21
【问题描述】:

更新我的项目以使用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;
}

【问题讨论】:

    标签: angular angular-httpclient


    【解决方案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'];
        })
      )
    

    ;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-27
      • 2021-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-08
      • 2020-02-05
      • 2018-07-25
      相关资源
      最近更新 更多