Mapping an HTTP object to a model

Currently facing an issue with mapping an http object to a specific model of mine, here is the scenario I am dealing with:

MyObjController.ts

class MyObjController {
        constructor (
            private myObj:myObjService,
            private $scope:angular.IScope,
            private modal,
            private notifier,
            private $translate,
            private $state,
            public items:MyObjModel[],
            public loading
        ) {
            this.loading = this.myObj.all();

            this.loading.then((allItems) => {
                this.items = allItems;
            });
        }
}

MyObjService.ts

all () : angular.IPromise<MyObjModel[]> {
            let uri = `/myuri`;

            return this.api.get(uri).then((response:any) => {
                return _.map(response.data, MyObjModel.create);
            });
        }

MyObjModel.ts

export class MyObjModel {
        constructor () { }

        id:string;
        name:string = '';
        organizationId:string = '';

        static create (apiResponse) {
            let model = new MyObjModel();

            model.id = apiResponse.Id;
            model.name = apiResponse.Name;
            model.organizationId = apiResponse.OrganizationId;

            return model;
        }
    }

The current approach seems problematic as _.map processes each value from response.data independently by creating separate instances of MyObjModel for each property and then forming an array of models. Seeking a solution where the entire response.data can be passed to the create() function to map values to a single instance of the model, returning that singular model instead.

Appreciate any assistance provided!

Answer №1

It is advised to utilize the following code:

getAll(): angular.IPromise<MyObjModel[]> {
            let uri = `/myuri`;

            return this.api.get(uri).map(data=><MyObjController>data.json())).toPromise();
            });
        }

Consider using an interface instead of a class with constructor as it is the recommended practice.

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

Vue is unable to capture Cordova events

Creating a hybrid app using Cordova while incorporating VueJS for routing and AJAX requests has presented some challenges for me. Despite my efforts, I have been unable to capture certain Cordova events. Even the essential deviceReady event seems to be el ...

Is there a way to display the number of search results in the CodeMirror editor?

After conducting some research on how to integrate the search result count in Codemirror like the provided image, I was unable to find any solutions. I am currently working with Angular and utilizing ngx-codemirror, which led me to realize that editing the ...

Troubleshooting Display Issue with Nested Div Selection in jQuery Tooltips

I have a long list of data consisting of 30-50 rows, each row needing its own distinct tooltip. Creating unique IDs for each row would require unnecessary JavaScript code. My goal is to utilize jQuery to retrieve the tooltip from the nested <DIV> wit ...

Leveraging latitude and longitude data from an API to create circles on the AGM platform

I need assistance with utilizing location data from recent earthquake events to center a circle on Angular Google Maps. Can anyone provide guidance on how to achieve this? The API call provides the following data: 0: --geometry: ---coordinates: Array( ...

Understanding the Document.ready function?

Recently, I came across some websites that follow this specific pattern: <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script> $(function (){...do some stuff with p ...

The parameter of type 'never' cannot be assigned with the argument of type 'number | boolean | undefined'

In my project, I am creating a validation input using TypeScript in Next.js. interface InputRules { required?: boolean min?: number max?: number minLength?: number maxLength?: number } I have defined an object that contains methods to handle val ...

Navigating between sibling components in Angular 1.5 using the component router

Is there a way to use the new component router in Angular 1.5 to display the sibling component alongside the main one within the ng-outlet directive? I am looking to showcase both the Detail View and the List View at the same time. Based on my understandin ...

Creating interconnected circles with lines utilizing canvas

I am currently utilizing the canvas tag to generate circles on a world map image. My objective is to link these multiple circles with lines using the Canvas tag. Although I have successfully drawn the circles, I am facing difficulty in drawing the connecti ...

Using react hooks, I am refreshing the product image by replacing it with the thumbnail image

I'm currently working on an e-commerce platform that resembles Amazon. In the product detail page, I want the right side image to update when I click on a thumbnail image on the left side. The issue I'm facing is that upon first loading, the def ...

What is the syntax for typing the router instance in Next.js?

I'm working on a password reset request form in my Next.js project. Here's the code I have: "use client"; import * as React from "react"; import { zodResolver } from "@hookform/resolvers/zod"; import { useForm } fro ...

Shared items found in a pair of entities

This function currently returns the difference between two objects, but I need to modify it so that it returns the common objects instead. Any assistance on how to achieve this would be greatly appreciated. Array example: var array1 = [ { "Name": " ...

What steps should I take to resolve the issue of 'this.reduce() not being a function'?

Here is my code : app.get("/", (req, res) => { const reducer = (acc, guildCount) => acc + guildCount; const results = client.shard.fetchClientValues('guilds.cache.size'); console.log(results) let guildCount ...

Ensuring all fetch requests are completed successfully before dispatching an action in React-Redux

I'm currently developing a React application and utilizing Redux to manage the state. Here is a snippet of the code: category-arrows.component.jsx: import React, { Component } from 'react'; import { connect } from 'react-redux'; i ...

How can a HTML element be clicked in JQuery to copy it into a text area?

Is it possible to select text from a list and insert it into a text box by clicking on it? I have developed a JSON API that retrieves a list of individuals from the database. Following this, there is a form with a text field that displays the list of peopl ...

Firefox does not support the event

// This function makes rows draggable within a table by utilizing mouse events. // It handles the drag initiation, movement, and stopping of the drag operation. makeRowsDraggable: function() { var dragInitiated = false; var startPageX, startPageY ...

An HTTP request is made with a JSON parameter to invoke a server-side GET function that does not

Having an issue with Angular's get method and unsure why the second server side function is being called instead of the first. Here is my code: var params = { "id": templateCategoryId }; this.http.get(this.appService.baseUrl + 'api/UserL ...

Difficulty encountered when converting objects into an array of a model within Angular

Below you will find the service code that I am using: export class ProductListService { constructor(private httpClient: HttpClient) { } getProducts(): Observable<IResponse> { return this.httpClient.get<IResponse>('https://local ...

having difficulties with angular subscribing to an observable

I am currently working on a service that retrieves a post from a JSON file containing an array of posts. I already have a service in place that uses HttpClient to return the contents of a JSON file. The main objective is to display the full content of the ...

Discovering the data types for node.js imports

When starting a node.js project with express, the code typically begins like this - import express = require('express') const app = express() If I want to pass the variable 'app' as a parameter in typescript, what would be the appropri ...

What is the best way to serialize data from non-form elements and make it easily accessible through params[:model]?

I have developed a unique Sinatra application that leverages an external API to load data and exhibit it on a page. Utilizing Sinatra, the information is retrieved and stored in a temporary model instance (which is NOT saved) for seamless access to all its ...