Ranjith Varatharajan
Ranjith Varatharajan

Reputation: 1694

Get only the required data from rest api

I have a wordpress blog installed for testing purpose. I have an angular app which consumes the wordpress rest api. The app calls an api which gets the categories. The json response has data which i'm not going to use in my app. So I created a model with only the value which I needed like name,slug etc. But When I consoled the response, it is showing the entire data. how can I restrict it?

Code:

model

  export interface BlogCategoryModel {
    id: number;
    name: string;
    slug: string;
    parent: number;
  } 

service

  getCategories(): Observable<BlogCategoryModel[]> {
    const url = 'https://blog.varanjith.com/wp-json/wp/v2/categories';
    return this.http.get<BlogCategoryModel[]>(url);
  }

component

  ngOnInit() {
    this.blogService.getCategories().subscribe((x: BlogCategoryModel[]) => {
      console.log(x);
    });
  }

output

enter image description here

Why I'm seeing count and description in the console? Whats happening there? I haven't included count and description in the BlogCategoryModel

Upvotes: 1

Views: 1864

Answers (2)

Evaldas Buinauskas
Evaldas Buinauskas

Reputation: 14097

Double check how typescript and HTTP client actually works : )

If you supply type parameter to HTTP client, it's not going to do anything with the response, only assign a type definition to it. This type definition can be really anything.

It's your job to consume it and pick only these properties that you actually need.

So in your case, you need to map your response first using map pipe and then map over categories array and pick required properties.

getCategories(): Observable<BlogCategoryModel[]> {
    const url = 'https://blog.varanjith.com/wp-json/wp/v2/categories';
    return this.http
        .get<BlogCategoryModel[]>(url)
        .pipe(
            map(categories =>
                categories.map(({ id, name, slug, parent }) => ({ id, name, slug, parent }))
            )
        );
}

This is a Stackblitz demonstrating it.

Upvotes: 5

Ivan Frolov
Ivan Frolov

Reputation: 103

Typescript itself doesn't say to api what it should and should not return. To use only those fields from your model you should handle the response in map operator:

getCategories(): Observable<BlogCategoryModel[]> {
    const url = 'https://blog.varanjith.com/wp-json/wp/v2/categories';
    return this.http.get<BlogCategoryModel[]>(url).pipe(
       map((result: any[]) => {
           return result.map((category: any) => {
               return {
                   id: caregory.id,
                   name: category.name,
                   slug: category.slag,
                   parent: category.parent
               }
           })
       })
    );
  }

Upvotes: 0

Related Questions