Developing a dynamic object deserializer in TypeScript/Angular 2

My background is in C# where I have experience working in a dynamic and reflective manner. Now, I am transitioning to TypeScript for writing a class and trying to apply similar principles.

To provide context, I am converting an existing application into a web app. The backend developer is reluctant to make significant changes to support JSON effectively. Hence, the plan is to send back JSON data structured like this:

{
        Columns: [
            {
                "ColumnName": "ClientPK",
                "Label": "Client",
                "DataType": "int",
                "Length": 0,
                "AllowNull": true,
                "Format": "",
                "IsReadOnly": true,
                "IsDateOnly": null
            }
        ],
        Rows:[
            0
        ]
    }
    

I intend to create an Angular class that extends Response and includes a specialized method called JsonMinimal that can interpret this type of data and return an object accordingly.

import { Response } from "@angular/http";

    export class ServerSource
    { 
        SourceName: string;
        MoreItems: boolean;
        Error: string;
        ExtendedProperties: ExtendedProperty[];
        Columns: Column[];
    }    

    export class ServerSourceResponse extends Response
    { 

        JsonMinimal() : any
        { 
            return null; 
        }

    }

While I understand that StackOverflow does not provide complete solutions, I seek guidance on structuring a dynamic response within TypeScript without encountering errors. This particular developer has numerous server-side methods, all returning strings in either JSON or XML format. My goal is to merge column and row data to build a comprehensive object that encapsulates these combined units.

An example scenario post-mapping the data to a basic object would involve:

var data = result.JsonMinimal() as LoginResponse; // Mapping the object correctly once the required data is integrated.

    var pk = data.ClientPK.Value;
    

Answer №1

It seems like you're not quite clear on the concept, but perhaps starting with a straightforward approach would be helpful. Angular's http get method provides an observable that can seamlessly map the response to either an object or an array of objects. It is also versatile enough to handle custom mapping/transformation tasks. I recommend exploring this functionality initially.

Consider the following example:

getProducts(): Observable<IProduct[]> {
    return this._http.get(this._productUrl)
        .map((response: Response) => <IProduct[]> response.json())
        .do(data => console.log('All: ' +  JSON.stringify(data)))
        .catch(this.handleError);
}

In this snippet, I'm converting a json response into an array of Product objects defined by an IProduct interface. As it is essentially a "lambda" function, any additional code can be included here to manipulate data as needed.

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

Unable to deploy Angular2 application using Cli

i clicked on this link; https://github.com/angular/angular-cli/wiki npm version is 5.0.1 node version is 6.11.0 i executed the following command: npm install -g @angular/cli here's what I tried to fix it: npm uninstall -g @angular/cli npm cach ...

What is the best approach to deserialize JSON that may contain either an object or an empty array, and if it is an object, it is in a "Dictionary" format?

I have encountered JSON data in a specific format that I cannot control. The data includes information about different countries, their codes, and names. { "response": { "status": 1, "httpStatus": 200, ...

Tips for efficiently indexing JSON data in PostgreSQL version 9.2

Is there a method for indexing JSON data in PostgreSQL 9.2? Here is an example of the data format: [ {"key" : "k1", "value" : "v1"}, {"key" : "k2", "value" : "v2"} ] If I want to index all the keys, how would I go about doing that? Thank you. ...

My HTML files are not getting bundled by Webpack

Despite including dependencies for HTML loaders in my Angular 2 application, webpack is not bundling my HTML files along with the rest of the files it generates. I have tried using both "html-loader" and "html-webpack-plugin," but to no avail. My webpack ...

Can you explain the significance of syntax in sample code (typescript, react)?

const sampleFunction: (inputString: string) => string = inputString => { return inputString.split(""); } I'm a bit confused about the code below and would appreciate some clarification. I understand that only "string" as a type is accepted, b ...

Unable to access the API within Angular using a web browser

My Angular application is hosted within an ASP.NET Core application on IIS. The API controller of the ASP.NET Core application can be accessed using the HTTP client in Angular as well as in a C# console application. However, I am facing an issue where I c ...

Angular (15) Encountering difficulties in expanding a typed FormGroup

Currently, I am experimenting with typed FormGroup. This is what I have created so far: export interface CustomFormControls { name: FormControl<string|null> content: FormControl<string|null> } export class CustomForm extends FormGroup< ...

Is there a way to automatically close the previous accordion when scrolling to a new one on the page?

Currently, I am working with the material-ui accordion component and facing an issue where all accordions are initially opened. As I scroll down the page and reach a new accordion, I want the previous ones to automatically close. The problem arises when tr ...

Unit testing in Angular ensures that a property is always defined and never undefined

I'm struggling to understand why this basic test isn't functioning properly. BannerComponent is not supposed to display a welcome message upon construction Expected 'welcome' to be undefined. // Component @Component({ selector: &ap ...

Is it possible to utilize a local JSON file path in conjunction with the Google Maps API?

According to the details provided in this documentation: Is it possible to substitute: map.data.loadGeoJson('https://storage.googleapis.com/maps-devrel/google.json'); with a local path like: C:\path\file.json ? or does it need to ...

Create a .d.ts file for a custom JavaScript file

I am working on an application written in JavaScript and considering incorporating TypeScript for a new feature. Currently, I have a base class defined in JavaScript as shown below: // base.js module.exports = function BaseClass () { // ... ... }; M ...

Tips for building a calculated field within Angular's reactive forms

I have recently implemented a form in my application and here is the code snippet: mapForm = this.fb.group({ name: ['', Validators.required], view: this.fb.group({ width: ['', Validators.required], height: [' ...

Exploring nested tables in JSON array within a parsing table for Android application

Having trouble extracting data from a JSON file. Can someone assist me? I've received a JSON array from the server and parsed the JSON objects as shown below: public ArrayList<ArrayList<Object>> parseAllTable(JSONObject object) { ...

Querying Firebase's real-time database for specific sub-child data

Here is the structure of my database: https://i.sstatic.net/Tduqg.png I have successfully retrieved all the documents by querying the userId: this.orderListRef = firebase.database().ref(`/orderList`); this.orderListRef.orderByChild('userId').eq ...

Guide to transforming a JsonArray into a Hashmap

I successfully obtained a jsonarray from a json string, however I am unsure of how to incorporate it into a Hashmap with a String indicating the type of cargo and an Integer representing the quantity. The provided string: "cargo":[ {"type":"Coals" ...

Error messages are being generated by Angular CLI due to an unclosed string causing issues with the

After incorporating styles from a Bootstrap theme into my Angular 8 project and updating angular.json, I encountered a compile error displaying the following message: (7733:13) Unclosed string 7731 | } 7732 | .accordion_wrapper .panel .panel-heading ...

Deciphering JSON in C#

Looking for help with parsing JSON data from the Google AJAX Search API? Check out this URL to see how to display the results. If you're new to C# and .NET, consider using JSON.NET for a simple solution to handle JSON data. UPDATE: Issue resolved wit ...

Can you please specify the format of this list?

When I receive data in the following format: "result": {"FirstData": {"One": 1, "Two": 2,... Firstly, what is this typically called in Java (2D array)? Secondly, how can I iterate over this to extract the strings? I know that if I only had "FirstData" ...

Retrieving Posts from Extensive JSON Data

I'm currently working on a project where I am coding a system to monitor updates on the Ontario Immigrant Nominee Program Updates page and then send out email alerts whenever a new article is posted. Initially, I implemented this in PHP but now I want ...

What is the method for executing a custom command within the scope of a tree view item?

I am trying to implement a custom "ping" function in my VS Code Extension that will send the details of a selected treeview object. Despite looking at various examples, I have been unable to properly build and register the command. Although I can invoke th ...