Riches
Riches

Reputation: 37

Angular 7 - HttpClient problem with .json()

Im trying to transform my get response from json into an array:

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

And i know that when im using HttpClient instead of Http there is no need to use .json() but im struggling with the syntax.

Upvotes: 3

Views: 1173

Answers (3)

TheBosti
TheBosti

Reputation: 1425

You should look into posts property of API response, something like this (simplified using 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
        )
    )
  );
}

Now results is an array of PostItem enter image description here

I have created a working demo, you can check it here -> https://codesandbox.io/s/78w2vl0p0

Upvotes: 2

Biplab Malakar
Biplab Malakar

Reputation: 788

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

Upvotes: 0

kauppfbi
kauppfbi

Reputation: 825

Try it with this syntax:

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

The important part is, that you use map within a pipe. And as you already mentioned res.json is not neccessary since introduction of HttpClientModule

Upvotes: 0

Related Questions