Automapper for AngularJS to format results retrieved from a RESTful service

When using the $resource service for data access from a restful service, I encounter a small challenge. The JSON data retrieved is in the following format:

{
    "name_surname": "john_smith",
    "years_of_employment": "10"
}

However, I would like to map it to a domain object of the Employee class below:

class Employee {
    constructor(public FullName: string, public YearsOfEmployment: number) { }
}

There seems to be a mismatch between the property names inside the domain class and the JSON fields. Is there an AngularJS module available that can help with mapping between these two structures, and what would be the most elegant way to achieve this?

Answer №1

This code snippet is a valuable tool in my current project, allowing me to easily map shortened properties to more readable ones during development. Feel free to use it in your own projects.

(function (angular) {
    "use strict";

    angular.module("services.mapper", []).service("mapper", [function ()      {
        var models = {
            employeeModelContract: {
                name_surname: "FullName",
                years_of_employment: "YearsOfEmployment"
            } 
        };

        return {
            map: map,
            models: models
        }

        function map(smallObject, contract) {
            var largeObject = {};
            for (var smallProperty in contract) {
                if (contract.hasOwnProperty(smallProperty)) {
                    largeObject[contract[smallProperty]] = smallObject[smallProperty];
                }
            }
            return largeObject;
        }
    }]);
})(angular);

Usage:

var mappedObject = mapper.map(yourJson, mapper.models.employeeModelContract);

UPDATE 1 (Typescript version):

class MapperService implements ng.IServiceProvider {

    employeeModelContract:Object= {
        name_surname: "FullName",
        years_of_employment: "YearsOfEmployment"
    };

    $get() { 
        return this;
    }

    map(smallObject, contract): Object {
        var mappedObject: Object = {};
        Object.keys(contract).forEach(contractProperty => {
            if (contract.hasOwnProperty(contractProperty)) {
                mappedObject[contract[contractProperty]] = smallObject[contractProperty];
            }
        });
        return mappedObject; 
    }
}

class Employee {
    constructor(public FullName: string, public YearsOfEmployment: number) { }
}

class Controller implements ng.IController {

    constructor(private mapper : MapperService){}

    static $inject = ["MapperService"];

    json: Object = {
        "name_surname": "john_smith",
        "years_of_employment": "10"
    }

    $onInit(): void {
        var mapped = <Employee>this.mapper.map(this.json, this.mapper.employeeModelContract);
    }
}

angular.module("mapper", []).controller("Controller",Controller).provider("MapperService", MapperService);

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

Tips on specifying a default value when receiving data from an API

I am working with a dropdown list that is populated from an API call. Here is my code snippet: <label>User Code:</label> <select ng-options="c as c.User for c in userList" ng-model="selectedUser" id="search3"> </select> To fet ...

Experiencing an Internal Server Error while attempting to upload a product using AngularJS in the MEAN Stack

I'm currently struggling with an Internal Server error while trying to add a product through the http service ($http.post) in AngularJS. To provide you with the necessary details for assistance, here are the key files involved: **index.js : This file ...

Selection dropdown not being populated by ng-options

After trying numerous examples to implement the changes, I am still facing issues. Even though I have an ng-model and clearly defined the object property I want to receive, it is not functioning as expected. Any assistance would be appreciated. Here is th ...

AngularJS modal directives trigger a reset of $scope variables

I am developing a custom AngularJS application that needs to handle and store all the checkbox selections made by the user in a simple array of IDs. The functionality includes displaying a modal when the open button is clicked, allowing the user to perform ...

Indicate a specific type for the Express response

Is there a method to define a specific type for the request object in Express? I was hoping to customize the request object with my own type. One approach I considered was extending the router type to achieve this. Alternatively, is there a way to refactor ...

Utilizing the moment function within an Angular application

I've successfully added the library moment.js by running: npm i moment I've included it in scripts and attempted to import it in module.ts. However, when I try to use moment in component.ts, I'm getting an error that says: 'canno ...

Instantiate a fresh object using the new keyword followed by the Class constructor, and if desired,

I'm looking for a class that I can easily create new instances from and optionally assign properties using the constructor. For instance: class Person { name: string; age: number; constructor(props: {name?: string, age?: number}) { this.nam ...

Leveraging the Power of JavaScript within Angular 12

Currently, I am in the process of learning how to utilize Angular 12 and am attempting to create a sidenav. While I am aware that I can use angular material for this task, I would prefer not to incorporate the associated CSS. My goal is to integrate this ...

Creating a custom URL in a React TypeScript project using Class components

I have been researching stack overflow topics, but they all seem to use function components. I am curious about how to create a custom URL in TypeScript with Class Components, for example http://localhost:3000/user/:userUid. I attempted the following: The ...

Strange behavior of Lambda function in Typescript

Within a larger class, I'm working with the following code snippet: array.map(seq => this.mFunction(seq)); After compiling using the tsc command, it becomes: array.map(function (seq) { return _this.mFunction(seq); }); Everything seems fine so f ...

What is the best method for connecting a ref to a component that I am duplicating with React.cloneElement?

Hi everyone! I'm trying to pass a ref into my component so that I can access the variables on the component like state. The only problem is, I'm having trouble getting it to work. It needs to be functional for both classes and functions. Every t ...

Django view is not able to receive data posted by Angular resource

I have successfully implemented an angular resource with the following code snippet: var services = angular.module('Services', ['ngResource']). // SEND_REPLY_SMS factory('SendSMS', ['$resource', function($resource){ ...

Using typescript, we can pass a generic class as a parameter to a function

Currently, I am faced with the challenge of passing a class reference as a function parameter, and then calling a static method on this particular class. Additionally, there is a possibility that in the future, I may need to instantiate the class and inclu ...

Ensure that missing types are included in a union type following a boolean evaluation

When working with typescript, the following code will be typed correctly: let v: number | null | undefined; if(v === null || v === undefined) return; // v is now recognized as a `number` const v2 = v + 2; However, if we decide to streamline this process ...

Error: The JSON file cannot be located by the @rollup/plugin-typescript plugin

I have recently set up a Svelte project and decided to leverage JSON files for the Svelte i18n package. However, I am facing challenges when trying to import a JSON file. Although the necessary package is installed, I can't figure out why the Typescri ...

Angular 2: Encounter with 504 Error (Gateway Timeout)

I am struggling with handling errors in my Angular 2 application. Whenever the backend server is offline, an uncaught error appears in the console: GET http://localhost:4200/api/public/index.php/data 504 (Gateway Timeout) This is how my http.get me ...

Issue with directive implementation of regex test as attribute - validations in typescript and angular

I am currently working on a project to create a module with custom validation directives. These validations are implemented using regular expressions (regex). The specific error I encountered is: Error: [$injector:unpr] Unknown provider: REG_EXPProvid ...

Tips for creating a window closing event handler in Angular 2

Can someone guide me on how to create a window closing event handler in Angular 2, specifically for closing and not refreshing the page? I am unable to use window.onBeforeunLoad(); method. ...

In Angular, make a call to a second API if the first API call times out after a specified period

In the event that my API does not return data within 5 seconds, I need to call a different one. Attempted implementation: this.service.returnData1(param1, param2) .pipe(timeout(5000), finalize(() => this.callSecondApi())) .subscribe( data => { ...

Vue.js is known to issue a series of alerts, one of which includes: "Invalid prop: type check failed for prop 'items'. Expected Array, received String with value ''.”

I currently have my front-end set up using vue-cli and the backend utilizing express. The processing time for fetching data from the backend is 1.7 seconds, but when I make the request under the mounted() lifecycle hook in Vue, I receive warnings because V ...