The data returned from the API is intact, yet certain fields remain unassigned

When I make a call to an API, I have created a simple model that matches my angular interface exactly.

The issue I am facing is that even though I define the variable where I push the data into of that interface type, it still shows the object fields as undefined. I'm not sure why this is happening, so if anyone can point out any simple mistake I may be unknowingly making, I would appreciate it.

This is the method in my service that calls the api:

    var projectsArray: Array<IDevProject> = [];
    var project : IDevProject;
    return this.http.get<IDevProject[]>(this.baseUrl + 'projects').pipe
    (
      map(data => {
        console.log(data);
        for (const id in data)
        {
          if (data.hasOwnProperty(id))
          {
            console.log("Checking Name >>>> " + data[id].Name);
            projectsArray.push(data[id]);
            project = data[id]; // checked with single objects, they also return properties as undefined
            
          }
        }
        return projectsArray;
      })
    );

This is how I call my service from ngInit (The parameter passed through is irrelevant):

projectsArray: Array<IDevProject> = [];

this.devService.getAllProjects(this.cardType).subscribe(
      data => {
        this.projectsArray = data;
        // console.log(data)
        // console.log(this.projectsArray.length);
        this.getArrayCount();
        // console.log(this.manyProjects)
        this.setMinSixDisplayArray();
      }   
    );

Finally, this is the interface used to bind the variable:

export interface IDevProject 
{
    Id: number;
    Name: string;
    Description: string;
    Image: string;
}

Link to the console image for reference: https://i.sstatic.net/rSDHm.png

Answer №1

It appears that you are utilizing Pascal case for the interface as well as attempting to access the properties. It would be more appropriate to utilize camelCase, especially since the API response uses camelCase according to the console output.

console.log("Checking Name >>>>> " + data[id].name);

Furthermore, it might be beneficial for you to consider using prettier to format your code within the Angular framework.

Answer №2

It is recommended to use lowercase letters for naming properties in your interface.

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

Updating the main window in Angular after the closure of a popup window

Is it possible in Angular typescript to detect the close event of a popup window and then refresh the parent window? I attempted to achieve this by including the following script in the component that will be loaded onto the popup window, but unfortunatel ...

How can we implement the json() method on a promise result that may be either a Response or void in Typescript?

When working on my React Native app, I encountered an issue with making an API call and using the json() method on the result. Here is the code snippet: await fetch(...) .catch(e => {...}) .then(res => res.json().then(...) An error was thrown by ...

Tips on adjusting the quantity of items in your cart

I'm currently working on a shopping cart project where I need to implement functionality to increase or decrease the quantity of items. However, I've encountered an issue where nothing happens when I click on the buttons. <div class="car ...

Can you explain the correct method for assigning types when destructuring the `callbackFn.currentValue` in conjunction with the `.reduce()` method? Thank you

I'm working with an array of arrays, for example: const input = [['A', 'X'], ['B', 'Y'],...]; In addition to that, I have two enums: enum MyMove { Rock = 'X', Paper = 'Y', Scis ...

Angular - The filter method cannot be used on Observables

I have a database with users who need to complete unique homework sessions. Each homework session has its own identifier, name, date, and other details. After fetching all the user's homework from the database, it is stored in a private variable call ...

The union type consisting of String, Boolean, and Number in type-graphql has encountered an error

I attempted to create a union type in type-graphql that represents the String, Number, and Boolean classes, but unfortunately, it was not successful. Does anyone have any suggestions on how to achieve this? export const NonObjectType = createUnionType({ ...

Is it possible to implement cross-field validation with Angular 2 using model-based addErrors?

Currently, I am working on implementing cross-field validation for two fields within a form using a reactive/model based approach. However, I am facing an issue regarding how to correctly add an error to the existing Error List of a form control. Form: ...

The struggle of implementing useReducer and Context in TypeScript: A type error saga

Currently attempting to implement Auth using useReducer and Context in a React application, but encountering a type error with the following code snippet: <UserDispatchContext.Provider value={dispatch}> The error message reads as follows: Type &apos ...

Highlighting in Coda on MacOS now supports TypeScript

Can anyone help me with getting my Coda editor to properly highlight TypeScript? I checked this page and it says that TypeScript is supported: But in my up-to-date version of Coda, the list of supported languages seems different. Is there a way to make Ty ...

Issues with page loading being halted by Angular2 child routes

Recently delving into Angular2, I am working on understanding routing, especially child routing. I have started my project based on the Angular2-seed project, focusing on setting up the routing structure. My routes are organized within functional modules ...

Developing in Angular 7 involves utilizing services with event and observable subscriptions inside the constructor, with the added functionality of calling

Picture this scenario: You want to create an Angular service that can function in two different modes: one using a REST endpoint and the other serving as a mock without relying on an endpoint. The REST service is intended for production use, while the moc ...

Solving TypeScript Error in React for State Destructuring

Recently, I've been working on creating a React component for AutoComplete based on a tutorial. In my development process, I am using Typescript. However, I encountered an issue while trying to destructure the state within the render suggestions metho ...

Dynamically modifying the display format of the Angular Material 2 DatePicker

I am currently utilizing Angular 2 Material's DatePicker component here, and I am interested in dynamically setting the display format such as YYYY-MM-DD or DD-MM-YYYY, among others. While there is a method to globally extend this by overriding the " ...

Error: Trying to access a property that is not declared on an empty object

Using a fully patched Visual Studio 2013, I am integrating JQuery, JQueryUI, JSRender, and TypeScript into my project. However, I am encountering an error in the ts file: Property 'fadeDiv' does not exist on type '{}'. While I believ ...

Troubleshooting ng module not found error when deploying Typescript + Angular app on Azure App Service using Azure DevOps pipeline

My Typescript and Angular application runs perfectly when tested locally. Now, I'm in the process of setting up a deployment pipeline using Azure DevOps to build and release it to an App Service running on Linux (Node.js web app). Although the pipel ...

When Angular site consumes a URL with parameters including an email hyperlink, the email address is being automatically rendered in lowercase

Hey there! I am currently working on a project that involves dotnetcore2 and angular. As part of the process, I am using Core functions like UserManager to generate a token called GeneratePasswordResetTokenAsync(). This token is then sent to the user via ...

When trying to import a CSS URL in Angular, the error "expectedcss(css-rparentexpected)" occurred

When working in VS code, I encountered a red error mark in the css file next to "400italic". How can I resolve this issue? Error:- ) expectedcss(css-rparentexpected); .css @import url(https://fonts.googleapis.com/css?family=Roboto:400, 400italic, 600 ...

What steps can I take to resolve the issue of the Error value not being iterable?

I encountered an issue in my table where I get the error message value is not iterable when there is no value to iterate through. How can I handle this error in my code? Snippet of Code: if (null != data && data) { data = data.map((item) => ...

Issues with loading Angular 9 application on Internet Explorer 11

Having trouble with my app not loading in IE 11 after adding ngx-treeview. Encountering the error (SCRIPT1002: Syntax error), Script Error Error point in vendor.js Unsure how to resolve this issue. Works fine in chrome and firefox, but in IE11 all I se ...

Adding flair to a object's value in React JS

In my React JS file, I have a map function that I am using to populate a select dropdown with options. const options = response.map(k => ({ value: k.id, label: k.description ? `${k.name} - ${k.description}` : k.name, })); I ...