Angular 7-.json()的HttpClient问题

时间:2019-03-16 10:22:29

标签: angular observable httpclient angular7

我正在尝试将我的get响应从 json 转换为数组

export class PostsService {
  apiRoot: string = "https://public-api.wordpress.com/rest/v1.1/sites/en.blog.wordpress.com/posts/?number=3";
  results: PostsItem[];
  loading: boolean;

  constructor(private http: HttpClient) {
    this.results = [];
    this.loading = false;
  }

  getPosts(term: string): Observable<PostsItem[]> {
    let apiURL = `${this.apiRoot}`;
    return this.http.get(apiURL)
    .map( res => {
      let results = res.json().results.map( item => {
        return new PostsItem(
          item.ID,
          item.post_thumbnail,
          item.date,
          item.title,
          item.url,
          item.author,
          item.avatar
        );
      })
      return results;
    });
  }
}

我知道,当我使用 HttpClient 而不是 Http 时,不需要使用.json(),但是我在语法上很挣扎。

3 个答案:

答案 0 :(得分:1)

您应该查看API响应的 posts 属性,如下所示(使用arrow functions进行了简化):

getPosts(): Observable<PostsItem[]> {
return this.http
  .get(this.apiRoot)
  .map(res =>
    res.posts.map(
      item =>
        new PostsItem(
          item.ID,
          item.post_thumbnail,
          item.date,
          item.title,
          item.url,
          item.author,
          item.avatar
        )
    )
  );
}

现在的结果是一个PostItem数组 enter image description here

我已经创建了一个有效的演示,您可以在此处进行检查-> https://codesandbox.io/s/78w2vl0p0

答案 1 :(得分:0)

尝试使用以下语法:

private getData(): Observable<Data> {
   this.http.get<DataType>(url).pipe(
     map(res => this.mapResponse(res))
   );
}

重要的是,您在管道中使用地图。 正如您已经提到的,自从引入HttpClientModule以来,res.json并不是必需的

答案 2 :(得分:0)

import { map} from 'rxjs/operators';
import {HttpClient, HttpResponse} from '@angular/common/http'

export class PostsService {
  apiRoot: string = "https://public-api.wordpress.com/rest/v1.1/sites/en.blog.wordpress.com/posts/?number=3";
  results: PostsItem[];
  loading: boolean;

  constructor(private http: HttpClient) {
    this.results = [];
    this.loading = false;
  }

  getPosts(term: string): Observable<PostsItem[]> {
    let apiURL = `${this.apiRoot}`;
    return this.http.get(apiURL).pipe(
         map(this.extractData)
    )
  }

  extractData(res: HttpResponse<any>) {
    const results = res['results'];
    results.map(item => {
      return new PostsItem(
        item.ID,
        item.post_thumbnail,
        item.date,
        item.title,
        item.url,
        item.author,
        item.avatar
      );
    });
    return results;
  }
}