What is the best way to assign JSON data to a Class variable within Angular?

In my code, I have a class called Projects

export class Projects {
project_id: number;
project_name: string;
category_id: number;
project_type: string;
start_date: Date;
completion_date: Date;
working_status: string;
project_info: string;
area: string;
address: string;
city: string;}

The corresponding Service class for this is

@Injectable()
export class ProjectsService {

  constructor(private http: HttpClient) {}

  //http://localhost:9090/projectInfo
private apiUrl = 'http://localhost:9090/projectInfo';

public findAll() {
  return this.http.get(this.apiUrl);
 }

 getProducts(): Observable<ProjectsModule[]> {
  return this.http.get<ProjectsModule[]>(this.apiUrl);
}

And the Component associated with these classes is

import { Component, OnInit } from '@angular/core';
import { ProjectsService } from '../projects.service';
import{Projects} from '../projects';
import { plainToClass, Transform, Expose, Type, Exclude } from 'class-transformer';
@Component({
  selector: 'app-project-list',
  templateUrl: './project-list.component.html',
  styleUrls: ['./project-list.component.css'],
  providers: [ProjectsService]
})
export class ProjectListComponent implements OnInit {

private projects:Projects[]=[];
stringObject: any;
  constructor(
   private projectsService: ProjectsService) { }
   vandana='rahul';
   
  ngOnInit() {
   this.getAllProjects();
   }


 getAllProjects() {
   this.projectsService.getProducts().subscribe((data: Projects[])=> {
      this.stringObject =JSON.stringify(data)
      let newTodo = Object.assign(new Projects(), data); 
      this.projects=  <Projects[]>this.stringObject;
      console.log("data  -"+ this.projects)
      console.log("Array  -"+ this.stringObject)
      console.log("data  -"+ this.projects[1].project_info)
      },
      
   err => {
   console.log(err);
   } 
   
  );
 
   }

However, when attempting to access properties of `newTodo` such as `newTodo.project_id`, they are returning undefined despite `newtodo` containing JSON data.

Here is the sample output:

https://i.sstatic.net/rwRUE.png

I am seeking assistance in accessing values like `newtodo.project_id`, `newtodo.project_name`, and others successfully

Answer №1

You have assigned a JSON data to this.projects.

The JSON data is

[{"projectNumber": 7, ... }]
.

Therefore:

  • this.projects[0] corresponds to { (which is the first character in the string)
  • "{".projectNumber results in undefined

It is recommended to assign the actual information to this.projects:

this.projects = data;

Remember that arrays in JavaScript start from index zero. With only one item in your array, you would access the projectNumber like this:

console.log(this.projects[0].projectNumber);

Additionally, make sure the properties of your Projects class align with the structure of your JSON. Also, consider renaming Projects to Project, and converting it into an interface instead of a class.

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

Utilize the power of modern Javascript to extract and display data from a JSON file by mapping an array and adding it

I've been attempting to construct a table from a JSON file by utilizing the map method in React. I've experimented with two approaches - one using map and the other using a for loop - but so far, I haven't been successful in getting the desi ...

Adjust parent div size based on image size increase

I am currently facing a situation where I have a page displaying an image, but sometimes it appears too small. In order to make the image larger, I have utilized CSS Transform and it is working well. However, the issue lies in the fact that the parent DIV ...

Issue with Angular 7: In a ReactiveForm, mat-select does not allow setting a default option without using ngModel

I have a Angular 7 app where I am implementing some reactive forms. The initialization of my reactive form looks like this: private initFormConfig() { return this.formBuilder.group({ modeTransfert: [''], modeChiffrement: [' ...

I'm having trouble understanding the distinction between this.query and this.query.find(). Can you explain the difference to me?

Currently, I am working on a MERN tutorial where I am developing a full E-commerce application. This is the class that handles querying and various other tasks. constructor(query, querystr) { this.query = query; this.querystr = querystr; con ...

Persistent vertical menu dropdown that remains expanded on sub menu pages

I am struggling to understand how to keep my menu sub items open when on the active page. Although I have tried similar solutions, I have not been successful in implementing them. I apologize if this question has been asked before. My approach involves usi ...

How to manage ajax URLs across multiple pages?

I have my website set up at http://example.com/foo/ within a directory, separate from the main domain. Through the use of .htaccess, I've configured the URLs to appear as http://example.com/foo/about/, http://example.com/foo/polls/, http://example.com ...

Ionic is encountering a problem with module build, specifically an error related to the absence of a file or directory

Using Ionic has led to encountering the following error message: Runtime Error Uncaught (in promise): Error: Module build failed: Error: ENOENT: no such file or directory, open '/Users/richardmarais/Development/ionic/theWhoZoo/src/pages/model/r ...

Execute a JavaScript function daily for each new user

Can someone help me understand how to execute a JavaScript/jQuery function that triggers a PopUp once for each new user visiting a webpage? Below is the code I need assistance with. $(window).load(function() { $('#index9').fadeIn("slow"); ...

Error 2300 in Vetur: Identical identifier found for '(Missing)'

Recently, I've been encountering a strange issue with Vetur in my typescript nuxt.js project. Every component, whether it's just an empty line or contains code, displays an error message on the first line. I can't pinpoint when this problem ...

Make a section of a draggable element unable to be dragged

I'm currently utilizing the Angular Material CDK, specifically the drag and drop functionality. I'm curious if there is a way to make one of the child div elements un-draggable while still enabling the parent div to be draggable? <div ...

Angular JS function is returning before the completion of the http.get request

I'm encountering an issue where this block of code is returning before it has received all the necessary information. Here's my current implementation: function (){ .... var promise = $http.get(...) promise.then (...){ //get info nee ...

Issues with simple jquery and javascript: unable to add the class ".has-error" and onclick event not properly defined

Currently, I am working with jQuery version 2.1.4 and JavaScript to implement a straightforward form validation using Bootstrap. During this process, I have encountered three peculiar issues. While I am confident that my jQuery code is properly functi ...

Exploring the Dependency Injection array in Angular directives

After some deliberation between using chaining or a variable to decide on which convention to follow, I made an interesting observation: //this works angular.module("myApp", []); angular.module('myApp', ['myApp.myD', 'myApp.myD1&a ...

Designing Object-Oriented JavaScript

Currently, I am in the process of developing a sophisticated JavaScript application. Utilizing an object-oriented design approach, I have organized my code into various files to enhance maintainability. In order to create my application, what is the best ...

The API key fails to function properly when imported from the .env file, but performs successfully when entered directly

Working with Vite has been quite an experience for my project. I encountered a situation where using my API key directly worked fine, but when trying to import it from .env file, I faced the error message in the console below: {status_code: 7, status_me ...

Using animation.width() in Javascript to create a countdown

Currently, I am working on creating a visual countdown for my users to indicate when an animation will finish. The code snippet below shows my initial attempt: function setClassAndFire(){ timer = setInterval(function () { t--; ...

Adjust the color of the text as it scrolls by

As I work on developing my website using the Neve Theme on WordPress, I have encountered an issue with customizing the header block. I am using a plugin to set a background color for the header after scrolling 100px down the page, but this makes the text h ...

MUI Error: Incorrect prop provided to menu item

I am encountering an issue with a React component that generates a list of elements, each containing a button to open a menu. The problem is that the props being passed to each menu are incorrect; they always reflect the props of the last element in the ...

"Learn the steps to seamlessly add text at the current cursor position with the angular-editor tool

How can I display the selected value from a dropdown in a text box at the current cursor position? I am currently using the following code: enter code selectChangeHandler(event: any) { this.selectedID = event.target.value; // console.log("this.selecte ...

Changing the visibility of a button based on a checkbox in JavaScript - here's how

Just starting out with JS and working on a react project. I need to toggle the visibility of a button from false to true when a checkbox is checked. Here's my code, I believe the logic is correct but it's not updating the UI. Any suggestions are ...