JavaScript/Typescript is throwing an error because it is unable to access the property 'username' of an undefined object

In my project, I am attempting to compile a list of Profile objects and then extract specific elements from each object in the list. To accomplish this, I have defined a public interface named Profile, imported it into my component, and instantiated a new Profile object while assigning values to attributes like id, username, and profilepic.

The issue arises when using *ngFor to iterate through the array. The iteration does not recognize the attributes id, username, or profilepic. Interestingly, when I log curP.username, the correct username is displayed in the console. This leads me to wonder if there is a mistake in my definition. Additionally,

console.log(this.displayActiverUser)
outputs the correct user list with id, username, and profilepic successfully.

Profile Interface:

export interface Profile {
    id: any;
    username: any;
    profilePic: any;
}

Component Implementation:

displayActiveUser = new Array<Profile>(10); // An array representing users
activeUserArray = new Array(10);

for (var n = 0; n < numAvalAcct; n++){
    let curP: Profile = {id: parseInt(this.activeUserArray[n][1]), username: this.activeUserArray[n][0], profilePic: "testurl"};
          console.log("username", curP.username);
          this.displayActiveUser[n] = curP;
        }

HTML Template Using *ngFor (The error occurs on the line with {{profile.username}})

<div class="list-group">
                <a *ngFor="let profile of displayActiveUser" (click)="followedNewUser(profile)" href="" target="popup" class="list-group-item list-group-item-action">
                    <img src="" class="rounded-circle" alt="profile picture" width="25" height="25"> {{profile.username}} 
                </a>
</div>

Output from

console.log(this.displayActiverUser)
:

0: {id: 135, username: "adamhaddad4", profilePic: "testurl"}
1: {id: 136, username: "ian.mccleary", profilePic: "testUrl"}
2: {id: 1, username: "dddd", profilePic: "testurl"}
3: {id: 134, username: "timtim1", profilePic: "testUrl"}

EDIT: The complete error message reads:

ERROR TypeError: Cannot read property 'username' of undefined
    at FollowForFollowComponent_a_6_Template (follow-for-follow.component.html:8)
    at executeTemplate (core.js:7329)
    at refreshView (core.js:7198)
    at refreshEmbeddedViews (core.js:8289)
    at refreshView (core.js:7222)
    at refreshComponent (core.js:8335)
    at refreshChildComponents (core.js:6991)
    at refreshView (core.js:7248)
    at refreshEmbeddedViews (core.js:8289)
    at refreshView (core.js:7222)

Answer №1

displayActiveUser = new Array<Profile>(10);
initialized an array containing ten undefined values.

The recommended approach is to utilize a map function for converting your input data into the desired output format. In contemporary JavaScript development, it's common practice to rely on functions like map and filter instead of traditional for loops.

this.displayActiveUser = this.activeUserArray.map(user => transformUser(user));

In this case, the transformUser function is responsible for mapping one object to another.

Answer №2

activeUsers = new Array<UserProfile>(10);

Creating an array with 10 available slots.

For more information, refer to Array constructor documentation.

Upon inspection, only 4 slots have been populated while the rest remain empty.

Answer №3

Implement an interface by creating a new class:

export interface ProfileInterface {
  id: any;
  username: any;
  profilePic: any;
}

export class Profile implements ProfileInterface {
  id = null;
  username = '';
  profilePic = null;
}

I have given the code a test run. Happy coding!

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

Limiting File Access for a Google Cloud Platform Bucket Using Node.js

Below is the code for my fileUploadService: import crypto from 'crypto'; var storage = require('@google-cloud/storage')(); uploadFile(req, bucket, next) { if (!req.file) { retur ...

Express.js is still displaying the 'Not Found' message even after deleting the initial code

Despite multiple attempts to resolve what I initially thought was a caching issue by completely removing all code from my server, I am still facing the same problem: The default error handling provided by Express Generator in the app.js file contains the ...

Extend GridView cell for file preview and download

Within my gridview, there is a column labeled "File Name" which includes the names of various files. I am looking for a way to click on a specific file name and be able to view its content as well as save or download the file. I am open to all suggestions ...

Using a Default Value in a Destructured Function Parameter Results in a ReferenceError

When working on setting a default value for the db in my CRUD functions for testing purposes, I encountered a peculiar issue that has left me puzzled. Here's the snippet of code that caused the trouble: import { db } from './firebase' func ...

Determine the RGB color values for specific coordinates within Adobe Illustrator

Currently exploring ExtendScript for JavaScript in Adobe Illustrator 2015. Is there a method to retrieve RGB values based on coordinates within the code below? // initializing document var doc = app.activeDocument; // defining x and y coordinates for colo ...

How can I update the background color of the specified element when the text changes without triggering a postback?

Seeking guidance on JavaScript as I am not very adept in it. We have a webpage where users upload .XLS/.CSV files and review the data before submitting it to our database. Users can edit cells in the uploaded document on our "review" screen before final su ...

Achieving second class using jQuery from a choice of two

Looking for assistance with retrieving the second class from an element that has two different classes. I attempted to use the split method but encountered some issues, can anyone provide guidance? js_kp_main_list.find('li#kp_r_04').addClass(&ap ...

Error in THREE.js: Failed to retrieve object at http://192.168.8.104:8080/[object%20Object] (Error code: 404) - Module: three.module.js

During my attempt to create a text loader in THREE.js, I encountered an error instead of getting the expected text output. three.module.js:38595 GET http://192.168.8.104:8080/[object%20Object] 404 (Not Found) I made various efforts to resolve this error ...

Using regex in javascript to strip HTML tags

I'm trying to clean up my document by removing all HTML tags except for <a>, <img>, and <iframe> using the following code: var regex = "<(?!a )(?!img )(?!iframe )([\s\S]*?)>"; var temp; while (source.match(regex)) { ...

Is there a way to adjust the dimensions of Google charts within a Bootstrap tab for a more customized appearance?

I've been working on a page that features tab navigation using Twitter Bootstrap and I want to include Google charts within each tab's content. However, I've encountered an issue where the charts are appearing in different sizes despite spec ...

Issue with <BrowserRouter>: TS2769: No suitable overload for this call available

I encountered this error and have been unable to find a solution online. As a beginner in typescript, I am struggling to resolve it. The project was originally in JavaScript and is now being migrated to TypeScript using ts-migrate. I am currently fixing er ...

Decoding JSON using JavaScript

I am dealing with a webservice that uses RestEasy to return a JSON object with a List element. When I try to parse the results in a JavaScript loop, everything works fine if there are two or more elements in the List. However, if there is only one element, ...

Issue with deleting and updating users in a Koa application

My goal is to create a function that deletes a specific user based on their ID, but the issue I'm facing is that it ends up deleting all users in the list. When I send a GET request using Postman, it returns an empty array. What am I doing wrong? I do ...

JQuery not properly validating inputs with required attributes after creation

I am currently developing a contact form that includes an "alternative address" <div id='alt'> with toggleable visibility. Inside this div, there is a required <input> field. I encountered an issue where toggling #alt twice (thus hidi ...

Tips on assigning array union as the return type of a function

I am working with a function parameter that accepts an array union, like this: (ClassA|ClassB)[]. How can I return either ClassA[] or ClassB[] from the function? When attempting to return type (ClassA|ClassB)[], I encounter the following error: Assig ...

NodeJS - Retrieving files from Google Drive

Here is a code snippet that I'm using to download files from Google Drive: function downloadDrive(fileId, callback) { var fileExt = fileId.split("."); var file = Date.now() + "." + fileExt[fileExt.length - 1]; var dest = fs.createWriteStream(". ...

Difficulty occurred when trying to import Polymer components

Currently, I am in the process of learning how to utilize Polymer. I meticulously followed the instructions provided exactly as specified here. However, upon reaching step 3 and adding the import for paper-checkbox, an error presented itself: Error: A c ...

Guide on transferring numerous files (50k+) from a folder to AWS S3 using node.js

Currently, my Node.js API on a Windows machine is generating numerous XML files that are later sent to an S3 bucket. The quantity of files sometimes surpasses 50k. For the uploading process, I am utilizing the aws-sdk package. Essentially, I iterate throu ...

Concealed checkbox value in jQuery

I have a problem with setting the hidden checkbox "marketingPhone" to TRUE when the "marketingAAA" checkbox is checked as true. This part works fine. However, if any other checkbox on the page is set to TRUE, then it also sets "marketingPhone" to TRUE. I ...

Modifications made in SQL are not reflected in Angular when using .NET Core

I recently encountered a challenge with my project, which is built on .NET Core 3.1 and Angular 7. After migrating the project to a new server, I started experiencing issues related to data synchronization between SQL database changes and the Angular compo ...