Mapping JSON data to a model in Ionic/Angular with the Model Adapter Pattern: A step-by-step guide

Here is an example of Json data:

{
    "restaurant": null,
    "details": [
        {
            "text": {
                "text": "Tea",
                "coordinateX": 311
            },
            "price": {
                "unitPrice": 5.0,
                "coordinateX": 389
            }
        },
        {
            "text": {
                "text": "Americano",
                "coordinateX": 311
            },
            "price": {
                "unitPrice": 41.24,
                "coordinateX": 205,
            }
        },
        {
            "text": {
                "text": "Latte",
                "coordinateX": 130
            },
            "price": {
                "unitPrice": 43.24,
                "coordinateX": 205,
            }
        }
    ]
} 

An issue arises when mapping the nested objects in the Json result API response to the corresponding models. Only the outermost object gets mapped.

The ImageResult Object - properly mapped:

export class ImageResult {
    constructor(
        public Restaurant: string,
        public CapturedDetails: Array<Details>
    ) {}

    static adapt(item: any): ImageResult {
        return new ImageResult(
            item.restaurant,
            item.details
        );
      }
  }

The Details Object - not correctly mapped and shows as a generic Object:

export class Details {
    constructor(
        public Text: Word,
        public UnitPrice: Price
    ) {}

    static adapt(item: any): Details {
        return new Details(
            item.text,
            item.price
        );
      }
  }

The Word Object - also not properly mapped and appears as a generic Object:

export class Word {
    constructor(
        public Text: string = '',
        public CoordinateX: number  = 0
    ) {}

    static adapt(item: any): Word {
        return new Word(
            item.text,
            item.coordinateX
        );
      }
  }

When calling the API, here's how the mapping process looks like:

GetText(formData: FormData): Observable<ImageResult> {
    return this.httpClient.post(this.getServiceUrl('TextCapture'), formData)
    .pipe(map(ImageResult.adapt));
  }

Answer №1

RetrieveText(formData: FormData): Observable<any> {
    return this.httpClient.post(this.getServiceEndpoint('TextRecognition'), formData)
        .map(Response => Response.json())
        .catch((error: any) => Observable.throw(error.json().message || 'Error connecting to server'));
}

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

In TypeScript and React, what is the appropriate type to retrieve the ID of a div when clicked?

I am facing an issue in finding the appropriate type for the onClick event that will help me retrieve the id of the clicked div. const getColor = (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => { const color = event.target.id; // ...

The process of comparing two arrays of objects in es6 and filtering out the unmatched arrays

In my Angular application, I'm attempting to retrieve only the updated array that was modified from the user interface. Within this scenario, I have two arrays in which one of the role names has been changed. My goal is to compare and extract the mod ...

Tips for adjusting collisions between models using three.js and oimo.js

I am currently working on implementing collision with an object using three.js by importing a model and then creating a body in Oimo to represent it. My problem arises from the fact that the center of the model does not align with the center of the object ...

Access data inside nested objects with specified data type

Imagine the code snippet below: type Parent = { children: Child[] } type Child = { label: string } const parent: Parent = { children: [ { label: 'label1' }, { label: 'label2' } ] } How can I use generics to ...

What is the process for integrating a JOI validator with a Firebase function?

Is there a way to incorporate JOI validator into Firebase functions as middleware? When calling a Firebase function, it looks something like this: exports.createUserAccount = region("europe-east1").https.onCall(createAccount); // createAccount is ...

Although Angular allows for CSS to be added in DevTools, it seems to be ineffective when included directly in

Looking to set a maximum length for ellipsis on multiline text using CSS, I tried the following: .body { overflow: hidden; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; } However, this approach did not work. Interesti ...

Angular Universal does not handle serving static files

I have a straightforward Angular Universal SSR (server-side rendering) application that is functioning well. The server successfully renders the HTML, but I am encountering an issue with static assets such as fonts, images, and icons not loading via the se ...

Compiling TypeScript to JavaScript with Deno

Currently experimenting with Deno projects and looking for a way to transpile TypeScript into JavaScript to execute in the browser (given that TS is not supported directly). In my previous experience with NodeJS, I relied on installing the tsc compiler via ...

In the latest version of Expo SDK 37, the update to [email protected] has caused a malfunction in the onShouldStartLoadWithRequest feature when handling unknown deeplinks

After updating to Expo SDK 37, my original code that was previously functioning started encountering issues with <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e7c6b6f6d7a23606f7a67786b23796b6c78667f79627a">[email prot ...

The @Input parameter is populated during an HTTP call

Within my app.component.ts, I am invoking a function from a service that returns the result of an HTTP request: questions: QuestionBase<any>[]; constructor(service: QuestionService) { this.questions = service.getQuestions().subscribe(val => c ...

Issues with applying different styles in a React Component based on prop values are hindering the desired outcome

I am currently working on a Display component that is supposed to show an item. The item should be styled with the css property text-decoration-line, applying line-through when the Available prop is set to false, and no decoration when set to true. Howev ...

Exploring Uppercase and Lowercase Filtering in NGXS for Angular Developers

I am encountering a problem with filtering and searching, specifically in matching the exact lowercase or uppercase of the string. Is there a way to search or filter regardless of the case sensitivity? For more information, please visit this link CLICK H ...

Customizing TinyMCE's font style menu options

Our platform utilizes TinyMCE as in-place editors to allow users to make live edits to content. However, a challenge arises when using a dark background with light text, as TinyMCE defaults to using this text color rather than black. https://i.sstatic.net ...

Converting the current date in Postgres to a date format in Typescript

My situation involves a specific date 2022-08-04 08:16:32.716904 // without timezone. This was created using the now() function in SQL as a timestamp with (6) milliseconds precision (i.e DateTime @db.Timestamp(6) with primsa). I am wondering how I can gen ...

When working with Angular and evaluating code, I encounter an issue related to the environment that

Here is my code snippet: let var1="environment.test"; console.log(eval(var1)); But when I run it, an error occurs: ERROR ReferenceError: environment is not defined However, if I modify the code to be like this: console.log(environment.test); it works ...

Troubleshooting mat-accordion title problem on mobile devices

Despite reading numerous blogs and conducting extensive searches on Google, I am still unable to resolve the CSS issue related to Angular material below. Your assistance in fixing this problem would be greatly appreciated. Desktop view: https://i.stack.im ...

Using Next.JS useRouter to access a dynamic route will result in receiving an empty object as the return value

I've encountered an issue with dynamic routing in my specialized calendar application built with Next.JS. One of my pages is working perfectly fine while the other is not functioning at all. The first page (working): // pages/date/[year]/[month]/[day ...

The component 'Form' cannot be utilized in JSX because its return type, 'ReactNode', is not a valid JSX element

I'm facing an issue with my Next.js application written in TypeScript after updating react-bootstrap. After the update, I am encountering the following error when attempting to use the Form component from react-bootstrap: react-bootstrap: ^2.10.3 @typ ...

Trigger Ionic's go back function when the hardware back button is clicked within the message app

Currently, I am utilizing the cordova-sms-plugin to integrate the native SMS app within my application. However, I have encountered an unexpected behavior where clicking the hardware back button in the SMS app leads back to my own app and triggers the Io ...

Encountering issues while retrieving date data from Firebase in Angular 6

this.qS = this.afDatabase.list('path', ref => { return ref.limitToLast(1000); }).snapshotChanges().map(changes => { return changes.map(c => ({ key1: c.payload.key,value1:c.payload.val() })); }); this.qS.subscribe(values =&g ...