Retrieve the essential information needed from the REST API

I have a test wordpress blog set up. To enhance the functionality, I developed an angular app that utilizes the wordpress rest api. The app makes a call to an endpoint to retrieve categories. However, the JSON response contains unnecessary data for my application. As a solution, I created a model with specific values such as name and slug. Yet, when I log the response to the console, it still shows all the data. How can I limit this?

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

https://i.sstatic.net/hUxsj.png

Why am I seeing count and description in the console output? What could be causing this issue? I did not include count and description in the BlogCategoryModel.

Answer №1

Make sure to understand the inner workings of TypeScript and HTTP client properly : )

If you provide a type parameter to the HTTP client, it won't directly impact the response; instead, it assigns a type definition to it. This type definition can vary based on your requirements.

It's crucial for you to parse this data and only extract the properties that are necessary for your application.

In your scenario, you should map the response first using the map method and then iterate through the categories array to select the essential 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 }))
            )
        );
}

Check out this Stackblitz example for a demonstration.

Answer №2

Typescript doesn't dictate to the API what data it must return or exclude. In order to selectively choose fields from your model, you can manage the response using the map operator:

fetchCategories(): 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: category.id,
                   name: category.name,
                   slug: category.slug,
                   parent: category.parent
               }
           })
       })
    );
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Learn how to configure an Angular2 Template Driven form element by implementing two-way binding and integrating template driven form validation techniques

Can anyone help me figure out the correct way to set up an Angular template driven form element for both validation and two-way binding? I've tried using ngModel in different ways, but cannot seem to achieve two-way binding without encountering issues ...

Currently, I am working on developing a to-do task manager using Angular 2. One of the tasks I am tackling involves updating the value

I'm facing an issue with managing to-do tasks. I would like to update the value of an option in a select dropdown when the (change) event is triggered. There are 2 components: //app.component.ts //array object this.dataArr[this.counter] = {id: this ...

Using Angular 2 to toggle the visibility of a component when hovering over and moving away from it

I have developed a custom filtering component in Angular 2, which I have integrated into the table header. My goal is to show the filter when the mouse hovers over a specific span, and hide it when the mouse moves away. <th> <span class="headCol ...

Elements are unresponsive to scrolling inputs

My Ionic 2 input elements are not scrolling to the top when the keyboard is shown. I've tried everything I could find on Google, making sure the keyboard disable scroll is set to false. However, I still can't figure out what's causing the sc ...

Utilizing pattern matching in switch statements

Imagine I have different APIs that provide data about various animals. Despite some shared properties, the JSON payloads for each animal type are quite unique and specific. To avoid chaos in my code, I am looking to create strongly typed TypeScript classe ...

Angular is unable to iterate through a collection of ElementRef instances

My list of ElementRef contains all my inputs, but adding listeners to them seems to indicate that textInputs is empty even though it's not. @ViewChildren('text_input') textInputs!: QueryList<ElementRef>; ngAfterViewInit(): void { ...

Angular 9: Subscribing triggering refreshing of the page

I've been working on an Angular 9 app that interacts with the Google Books API through requests. The issue I'm facing is that whenever the requestBookByISBN(isbn: string) function makes a .subscribe call, it triggers a page refresh which I' ...

Issue: Unrecognized element type in next.js while starting development server

Every time I run npm run dev, I encounter the following error: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from th ...

Transport parameter via routerLink to a different component

When I click on the link provided in the list-profile HTML document, I need to send a variable. However, the current code is not working and causing crashes. If more details are required, feel free to ask. List Profile Component HTML <div class="col c ...

Angular - Acquire reference to the <audio> element

Is there a way to access the methods of an audio tag within my component in order to implement play and pause functions based on click events? The current method I tried does not allow me to access the play() function. How can I correctly approach this? ...

Verify and retrieve information from the Dynamics CRM Web API with the help of Angular 2 (TypeScript)

How can one authenticate and query the Dynamics CRM Web API from a Single Page Application developed with Angular 2 (TypeScript)? Initial research indicates that: The Dynamics CRM (version 2016 or 365) instance needs to be registered as an application ...

Navigating with Angular inside an HTTP POST Observable and subscription

Whilst attempting to guide a user towards a dashboard within the response of an httpClient.post request, I have encountered a peculiar issue. The page navigates "successfully" (as evidenced by the URL bar) but unfortunately, most elements of the components ...

The PrimeNG FullCalendar feature seems to be malfunctioning and cannot be located

I've been working on integrating a FullCalendar module into my Angular 7 project. Despite following the steps provided in this link, I haven't had any luck: After executing this command: npm install <a href="/cdn-cgi/l/email-protection" clas ...

What are the steps for deploying an Angular 6 application on an Express server?

In my express server.js file, I have the following line of code: app.use(express.static(path.join(__dirname, '/dist/'))); This line is responsible for serving up the Angular app when users navigate to /. However, if the app has additional route ...

Discover the steps to include the property within the data model in Angular specifically meant for showcasing on the user interface list page

class UserIdentity { public uniqueID: string; public fullName: string; public bio: string; public service: string; public groupID: string; public userID: string; public secretKey: string; constructor(details?: any) { this.uniqueID = &a ...

How is it possible that this is not causing a syntax or compile-time error?

Oops! I made a mistake and typed : instead of = on line 2 of this code snippet. Why does Typescript allow this error? Isn't colon supposed to indicate a known Type for a property declaration? I'm pretty sure there's a reason encoded in the ...

Issues arise when attempting to override attributes within the HTML of a parent component in Angular

Why does overriding an attribute in a child class that extends from another not work as expected? Here's a made-up scenario to simplify the issue: Parent class file: gridbase.component.ts import { Component, OnInit } from '@angular/core'; ...

To use the ModuleWithProviders<T> in the angular-autofocus-fix package, you must provide 1 type argument

Upon successful installation of angular-autofocus-fix I have imported the AutofocusModule However, upon running the Angular project, I encountered the following error: ERROR in node_modules/angular-autofocus-fix/index.d.ts:4:23 - error TS2314: Generic ty ...

Disable button attribute in Angular unit testing when form is not valid

I have successfully implemented the functionality to disable a button when the form is invalid and enable it when the form is filled in properly. However, I am encountering difficulties with testing this feature: Here is the test that I wrote: it('s ...

Angular 8: A Guide to Updating Tags in innerHTML

Hello, below is the code I am working with: <span [innerHtml]="question.description | SafePipe: 'html'" style="font-weight:500;" class="ml-1"></span> Upon inspecting my website, I noticed that my <span> tag contains nested &l ...