Mapping a response object to a Type interface with multiple Type Interfaces in Angular 7: A step-by-step guide

Here is the interface structure I am working with:

export interface ObjLookup {
    owner?: IObjOwner;
    contacts?: IOwnerContacts[];
    location?: IOwnerLocation;
}

This includes the following interfaces as well:

export interface IObjOwner {
    lastName?: string,
    firstName?: string;
}

export interface IOwnerContacts {
    name?: string;
    address?: string;
    email?: string;
}

export interface IOwnerLocation {
    address?: string;
    city?: string;
    state?: string;
    zip?: number;
    country?: string;
}

Describing my response object structure, it looks like this:

{
    status: "success",
    is_error: false,
    errors: [],
    data: {
        owner: {
            lastName: "lovejoy",
            firstName: "reverend"
        }, 
        contacts: [
            {
                  name: "homer simpson",
                  address: "3 evergreen terrace, springfield, XX XX823",
                  email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5d353230382f1d2e2d2f34333a3b3438313933283e31383c2f73">[email protected]</a>"
            },
            {
                  name: "ned flanders",
                  address: "5 evergreen terrace, springfield, XX XX823",
                  email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0a646f6e4a7965676f69627f786962246d656e">[email protected]</a>"
            }
        ],
        location: {
            address: "the church",
            city: "Springfield",
            state: "XX",
            zip: XX823,
            country: "US"
        }
    }
}

There might be some syntax errors in the json response due to manual typing.

In order to handle this response efficiently, I believe using observables and mapping techniques are necessary. Here is a snippet of what I have so far:

export class SimpsonsService {
     public resourceUrl = 'www.example.com/api/simpsons';

     constructor ( protected http: HttpClient) {}

    find(name: string): Observable<EntityResponseType> {

        return this.http.get<ObjLookup>(`${this.resourceUrl}/${name}`)
           .pipe(
               map(respObj => {
                   const
               })
           );
        });
    }
}

I've attempted different approaches to extract the relevant data objects from the response and align them with their respective interfaces within ObjLookup.

How can I correctly parse and utilize the response.data.owner, response.data.contacts, and response.data.location objects?

Answer №1

Give this a shot

founder:  IObjFounder;
connections: IFoundContacts[];
area: IFounderLocation;

return this.http.get<ObjLookup>(`${this.resourceUrl}/${name}`)
           .pipe(
               map(respObj => {
                   this.founder= respObj.data.founder
                   this.connections= respObj.data.connections
                   this.area= respObj.data.area
                   //implement some logic here
               })
           );
        });

Answer №2

Simply typecast

    <IObjOwner>response.data.owner
    <Array<IOwnerContacts>>response.data.contacts
    <IOwnerLocation>response.data.location

To handle the situation where

data wasn't a property of response
, you can set the return type of response object as any. Alternatively, create a new interface that includes all the properties of the response object and assign the type of that interface to the response object.

export interface IDataResponse {
    owner?: IObjOwner;
    contacts?: Array<IOwnerContacts>;
    location?: IOwnerLocation
}

export interface IResponse {
    status?: string;
    is_error?: boolean;
    errors?: Array<any>;
    data?: IDataResponse;
}

Then, utilize it like this:

owner:  IObjOwner;
contacts: Array<IOwnerContacts> = [];
location: IOwnerLocation;

return this.http.get<ObjLookup>(`${this.resourceUrl}/${name}`)
           .pipe(
               map((response: IResponse)=> {
                  this.owner =  <IObjOwner>response.data.owner
                  this.contacts =  <Array<IOwnerContacts>>response.data.contacts
                  this.locations = <IOwnerLocation>response.data.location
               })
           );
   });

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

`When the component is loaded, subscribing to the event will work properly.`

I am facing challenges with handling data retrieved from a Database. I want to send it to a central service so that I can utilize it later when loading the components that require this data. The issue I'm encountering is that the central service appea ...

When using the requests library in Python, a post request is resulting in a 400 'Bad Request' error. Interestingly, the same request works perfectly

I am encountering a 400 error when my script calls a POST endpoint, despite the corresponding cURL request being successful. Here is the original cURL command: curl -X 'POST' \ 'http://localhost:8080/api/predict?Key=123testkey' ...

Encountering problems during installation of packages in Angular

Running into issues with commands like "ng add @angular/localize" or "ng add @ng-bootstrap/ng-bootstrap". As a newcomer, I'm struggling to interpret the error messages. I have included screenshots for reference. View angular version screenshot View e ...

Utilizing Typescript to implement an interface's properties

After declaring an interface as shown below interface Base { required: string; } I proceeded to implement the interface in a class like this class MyClass implements Base{ method(): void { console.log(this.required); } } However, I ...

Functions have been successfully deployed, but they are not appearing on the Azure Portal

I am experiencing difficulties deploying basic Typescript functions to Azure. Despite a successful deployment using VS code and confirmation in the Output window, I cannot see any functions listed in the Azure Portal under the Function App: https://i.stac ...

Create a TypeScript interface that represents an object type

I have a Data Structure, and I am looking to create an interface for it. This is how it looks: const TransitReport: { title: string; client: string; data: { overdueReviews: number; outstandingCovenantBreaches ...

Array of objects not being shown in select dropdown

I have a component with a dropdown feature. Below is the code snippet from the component: export class MyComponent { MyObjectArray: MyObject[] = []; constructor(private _service: MyService) } ngOnInit() { this._service.get().do((response): MyObjec ...

Angular 2 and 4 now have a specialized node module designed to create tree-like structures within the framework

Are there any node packages available for creating tree-like structures in Angular 2 or 4, similar to what is shown here ? I am looking for the ability to customize templates within the tree. Any suggestions? ...

The resolution of Angular 8 resolver remains unresolved

I tried using console.log in both the constructor and ngOnInit() of Resolver but for some reason, they are not being logged. resolve:{serverResolver:ServerResolverDynamicDataService}}, console.log("ServerResolverDynamicDataService constructor"); console ...

ERROR TS1086: A declaration of an accessor within an ambient context is not allowed. Accessor for firebaseUiConfig(): NativeFirebaseUIAuthConfig

Trying to create a Single Page Application with Angular/CLI 8. Everything was running smoothly locally until I tried to add Firebase authentication to the app. Upon compiling through Visual Studio Code, I encountered the following error message: ERROR in ...

TypeScript - Converting into individual compiled files

Currently, I am working on a project that consists of lengthy source files. While this is advantageous for imports, it poses challenges in terms of maintenance. For instance: /main/core.ts export type Foo { ... } export interface Bar { ... } export cla ...

Passing validators for reactive forms from parent to child components is proving to be a challenge

Currently, I have a situation where a parent form component is utilizing a child form component within an Angular reactive forms setup. While I am able to successfully set the values in the child form component, it seems that the validators are no longer f ...

Why isn't useEffect recognizing the variable change?

Within my project, I am working with three key files: Date Component Preview Page (used to display the date component) useDateController (hook responsible for managing all things date related) In each of these files, I have included the following code sn ...

The StreamingTextResponse feature is malfunctioning in the live environment

When I share my code, it's an API route in Next.js. In development mode, everything works as expected. However, in production, the response appears to be static instead of dynamic. It seems like only one part of the data is being sent. I'm puzzl ...

Having trouble retrieving the parameter sent through the router in Ionic 4

I am facing an issue in my Ionic 4 project where I am trying to send a parameter using the router but unable to retrieve it on the other page. Here is how my tabs.router.module.ts looks like: { path: 'tab2', children: [ { ...

What could be causing the issue of Vuejs 3.3 defineModel consistently returning undefined?

I am currently working with Nuxt version 3.5.1 and Vuejs version 3.3, however, I am encountering an issue where the defineModel macro always returns undefined. I am unsure why this is happening? <template> <input v-model="count"& ...

Steps for updating text within an object in Angular

details = [ { event: "02/01/2019 - [Juan] - D - [Leo]", point: 72 }, { event: "02/01/2019 - [Carlo] - N - [Trish]", point: 92 } ]; I am attempting to modify the text within the titles that contain - N - or - D - The desired outcom ...

Exploring the use of Jest for testing delete actions with Redux

I've been working on testing my React + Redux application, specifically trying to figure out how to test my reducer that removes an object from the global state with a click. Here's the code for my reducer: const PeopleReducer = (state:any = init ...

Separate the date format string into tokens

I am currently attempting to create a function that is able to transform a date format string such as %d/%m/%Y %H:%n where the variables are always denoted by a percentage sign followed by one character, into an array of tokens: ["%d", "/", "%m", "/", " ...