Using Angular 2 to map JSON data to a specific class using injectors

A new challenge has arisen that involves a specific class:

import { HttpClient } from '../services/http.service'
export class Project {
    constructor(
        private http: HttpClient
    ){
    }
    @JsonProperty('name')
    title: string;
    id:string;
    
    public getTitle(): string  {
        return this.title;
    }

    public getId(): string {
        return this.id;
    }

    public removeProject() {
        return this.http.delete("deleteurl"+this.id).map(() => {
            return true;
        })
    }

}

The main goal is to properly deserialize json objects like this:

import { JsonConvert } from "json2typescript";
getProjects():Observable<Project[]> {
        return this.http.get("getprojects").map((res:Response) => {
            var array: Project[] = [];
            for (let entry of res.json().files) {
                array.push(JsonConvert.deserializeObject(entry, Project));
            }
            return array;
        })
    }

An issue arises when attempting to map the json data to the classes due to an error linked to the injected HTTP service within the Project class

How do you suggest handling this? What would be considered best practice in this situation?

Answer №1

If you're looking to use the getProjects method in HttpClient, make sure you include the Injectable import in your service file.

   import { Injectable } from '@angular/core';
   import { Http, Response, Headers } from '@angular/http';
   import { Observable } from 'rxjs/Observable';

This is necessary for performing dependency injection in your Project class constructor.

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

Angular is unable to fetch the chosen option from a dropdown selection

Recently, I encountered an issue with a module form that appears as a pop-up. Within this form, users can input data required to create a new object of a specific class. One field allows users to select a ventilation zone for the new room object being crea ...

Following the execution of the commit, the variable remains in a state of

I'm currently in the process of creating a new task. I was expecting the result to be 'created task with title', but the title is empty because 'formData' is still reactive. Below is an example of the code: // index.vue <form ...

Issue encountered in Angular 2 while attempting to import TypeScript classes using a single file

Upon loading my Angular 2 application, I encountered the following error: EXCEPTION: Error: Uncaught (in promise): Unexpected piped value 'undefined' on the View of component 'DashboardComponent' An interesting observation is that by ...

No response from NgClass after executing the function

In my NgClass function, I make use of an array that is populated in the ngOnInit lifecycle hook. Within ngOnInit, the prepareRezerwation() function creates a variable called colorRezerwation: this.nodeService.getRezerwations(this.minMax).subscribe(re ...

A guide on converting JSON to TypeScript objects while including calculated properties

I have a standard JSON service that returns data in a specific format. An example of the returned body looks like this: [{ x: 3, y: 5 }] I am looking to convert this data into instances of a customized TypeScript class called CustomClass: export class ...

Retrieving a specific data point from the web address

What is the most efficient way to retrieve values from the window.location.href? For instance, consider this sample URL: http://localhost:3000/brand/1/brandCategory/3. The structure of the route remains consistent, with only the numbers varying based on u ...

Exploring the emission of Vue 3 with the Options API through typing

Is there a way to declare emits in Vue 3 Options API similar to the Composition API approach? Based on the Composition API documentation: (docs) <script setup lang="ts"> // type-based const emit = defineEmits<{ (e: 'change', ...

Setting angular variables by assigning form values

My current reactive form setup looks like this: this.editform = new FormGroup({ 'username' : new FormControl(null,[Validators.required]), 'password' : new FormControl(null,[Validators.required]), 'full_name' : ne ...

Issue with package: Unable to locate the module specified as './artifacts/index.win32-ia32-msvc.node'

I am encountering an issue while using Parcel for the first time. When I execute npx parcel .\app\index.html, I receive the following error: Error: Module not found './artifacts/index.win32-ia32-msvc.node' Require stack: - C:\Users ...

retrieve an object with enum keys that are indexed

I am faced with a situation where I have a collection of interdependent elements, each identified by a unique code (enumeration). My goal is to retrieve the list of elements that depend on a specific element, and then be able to reference them using myElem ...

The most recent version of Angular featuring the powerful Angular-anim

Currently, I am in the process of revamping an application that was initially developed using a combination of jquery, bootstrap, and kendo ui. Moving forward, the application will transition to an angular (2/4) and kendo framework. In the previous setup, ...

Stop child components from rendering until the parent controller has successfully resolved the data

My current scenario is as follows: I have an app.module that bootstraps the app.component The router in my application has a base href = '/' This router loads my home.component, which contains an onInit() method to fetch data from an API using ...

Enhancing VueJS by assigning types to refs on this.$refs to eliminate any potential TypeScript errors

Imagine a scenario where you have the following rough pseudo code: <v-menu ref="dmenu" other="stuff here" @change="save" > Later in your code, you reference it like this: save(val: string) { this.$refs.dmenu.save(val) } An error message p ...

Steps for configuring Types in Graphql Codegen

I have successfully implemented a Vue 3 component that utilizes Urql to query a Hasura graphql endpoint. The query is functioning properly, but I am now focused on enhancing the type safety of the component. My approach involves using graphql Codegen to g ...

Exploring the world of Angular and utilizing TFS for seamless

Embarking on a new Angular development journey, I have relied on Angular documentation to guide me through the process - from installing node packages to creating a new Angular project. However, I am now looking to integrate my development work into an ex ...

Angular 8 is throwing an error stating that the property 'token' is not recognized on the 'Object' data type

As a newcomer to Angular, I have been following the MEAN Stack - Mean Auth App Tutorial in Angular 2. However, since I am using Angular 8, some of the code is deprecated due to recent updates. I have encountered an issue with the code bel ...

AngularJS - Sending event to a specific controller

I am facing an issue with my page where a list of Leads each have specific actions that are represented by forms. These forms can be displayed multiple times on the same page. Each form has its own scope and controller instance. After submitting a form, an ...

Having trouble with animation transition in Angular 6?

When it comes to animating the opening and closing of a Sidenav, what are some best practices? animations: [ trigger('slider', [ state('open', style( {} )), state('closed', style( ...

The attribute 'X' is not present in the specified type 'IntrinsicAttributes & InferPropsInner'

I've been restructuring my code from a .js file to a .tsx file, as seen below: import React, { useEffect, useState } from 'react' import PropTypes from 'prop-types' import { checkMobile } from '../../utils/common' import ...

The specified main access point, "@angular/cdk/platform", is lacking in required dependencies

I recently updated my Angular app from version 8 to version 9. After resolving all compilation and linter errors, I encountered one specific issue that is causing me trouble: ERROR in The target entry-point "@angular/cdk/platform" has missing dep ...