List in Angular remains empty

I am facing an issue with populating a simple HTML list using Angular. The problem arises when trying to display the data in the list. When I use

console.log("getUserCollection() Data: ", data);
, it shows an array which is fine, but
console.log("getUser() Data: ", data);
displays an empty object since the list is not getting populated. How can I resolve this? Should I consider adding the async pipe to the code?

This is my Users.component.ts:

import { Component, OnInit } from '@angular/core';
import { AviorBackendService } from '../services/avior-backend.service';
import { UserCollection } from '../models/user-collection.model';
import { User } from '../models/user.model';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit {

  selectedItem: string;

  users: UserCollection;
  user: User;
  firstname: string;
  selectedUser: User;

  constructor(private aviorBackend: AviorBackendService) { }

  ngOnInit() {
      this.aviorBackend.getUserCollection().subscribe(data => {
      // tslint:disable-next-line: no-string-literal
      this.users = data['firstname'];
      console.log(this.users);
      console.log("getUserCollection() Data: ", data);
    });
  }

  clickItem(firstname) {
      this.aviorBackend.getUser(firstname).subscribe(data => {
      // tslint:disable-next-line: no-string-literal
      this.selectedUser = data['user'];
      console.log(this.selectedUser);
      console.log("getUser() Data: ", data);
    });
  }
}

This is my Users.component.html:

<div class="list-area">

  <div class="col-lg-12">

    <p class="list-header">Element overview</p>

    <div class="form-group">
      <label for="filter" class="lb-sm">Filter</label>
      <input type="text" class="form-control input-sm" name="filter" id="filter">
    </div>

   <select size="20" multiple class="form-control" id="elementlist" [(ngModel)]="selectedItem" (click)="clickItem(firstname)">
      <!-- maybe add | async pipe -->
    <option *ngFor="let user of users">
        {{user?.lastName}}, {{user?.firstName}}
      </option>
    </select>

  </div>

</div>

<div class="content-area">

  <div class="col-lg-12" *ngIf="selectedUser?.id">

  <p>Element contents {{selectedUser?.id}}</p>

  <div class="col-lg-12">
    <div class="form-group">
      <label for="firstName" class="lb-sm">First Name</label>
      <input type="text" class="form-control input-sm" name="firstName" id="firstName" [(ngModel)]="selectedUser.firstName">
    </div>
  </div>

  </div>

</div>


Update This is my getUser() method:

// Get user
  getUser(firstname: string): Observable<any> {
    const API_URL = `${SERVICE_URL}user/firstname/${firstname}`;
    return this.client.get(API_URL, this.httpOptions).pipe(
      map((res: Response) => {
        return res || {};
      }),
      catchError(this.handleError())
    );
  }

UPDATE 2

This is my user.model.ts:

import { Role } from './role';

// Modified from class to interface!
export interface User {
    id?: number;
    mandator?: number;
    loginId?: string;
    lastName?: string;
    firstName?: string;
    password?: string;
    eMail?: string;
    group: string;
    role: Role;
    active?: boolean;
    token?: string;
}

This is my user-collection.model.ts:

import { User } from './user.model';

export interface UserCollection {

    user: User[];

}

Answer №1

Revise your

retrieveUserRecords().subscribe()
service call:

this.users = data;

Instead of just assigning 'firstname' to users.

Update the User interface as well:

export interface User {
    _id: string;
    loginId: string;
    lastname: string;
    firstname: string;
    password: string;
    eMail: string;
    group?: string;
    role?: Role;
    active?: boolean;
    token?: string;
}

This adjustment aligns with the response from the backend model. Remember, you can always use map() for further customization in frontend model mapping.

Make sure to adjust your model in the .html file to match the updated names. For example:

{{user.lastname}}, {{user.firstname}}

Don't forget to update the click handler to

(click)="clickItem(user.firstname)"
:

<select size="20" multiple class="form-control" id="elementlist" [(ngModel)]="selectedItem">
      <!-- consider adding | async pipe -->
    <option *ngFor="let user of users" (click)="clickItem(user.firstname)">
        {{user?.lastName}}, {{user?.firstName}}
      </option>
</select>

Answer №2

<select size="20" multiple class="form-control" id="elementlist" [(ngModel)]="selectedItem" (click)="clickItem(firstname)">
      <!-- maybe add | async pipe -->
    <option *ngFor="let user of users">
        {{user?.lastName}}, {{user?.firstName}}
      </option>
    </select>

It seems that the code is trying to access a parameter firstname in the clickItem function without it being defined.

You may want to consider removing the firstname parameter and accessing the selectedItem property of your component instead.

clickItem() {
      this.aviorBackend.getUser(selectedItem).subscribe(data => {
      // tslint:disable-next-line: no-string-literal
      this.selectedUser = data['user'];
      console.log(this.selectedUser);
      console.log("getUser() Data: ", data);
    });

Update:

If you're looking for a more reactive example, you can check out this link: https://stackblitz.com/edit/angular-scdzjq Maybe trying a new approach like this could be beneficial for you.

Answer №3

Consider substituting the following code snippet

this.users = data['firstname'];

with this alternative

this.users = data;

Answer №4

Consider including a name attribute in the select element, for instance name="userSelection"

LATEST UPDATE: After reviewing the structure of the 'users' array you provided, it appears that you should utilize firstname instead of firstName, as well as lastname instead of lastName

In addition, you might want to simplify by using this.users = data; where data represents an array of user models

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

What is the best way to apply a filter to an array of objects nested within another object in JavaScript?

I encountered an issue with one of the API responses, The response I received is as follows: [ {type: "StateCountry", state: "AL", countries: [{type: "County", countyName: "US"}, {type: "County", countyNa ...

Ways to make an element disappear when clicking outside of it in Angular 7 or with CSS

After entering text into an input field and pressing the space key, a div called 'showit' will be displayed. However, I want this div to hide when clicking outside of it. See the code below for reference: home.component.html <input type="tex ...

How to utilize Enzyme to call a React prop in TypeScript

I'm currently in the process of converting my Jest tests from Enzyme to TypeScript, and I've come across a specific case that I'm unsure how to resolve. Essentially, I'm attempting to invoke a function passed as a prop to a sub-componen ...

Assigning a Value to a Dropdown Menu in Angular

I have some JSON data that contains a True/False value. Depending on whether it is true or false, I want a specific option in a Select Dropdown to be automatically selected. This is the HTML code using Angular 16: <select name="reportNo" id=& ...

Show images from an array of base64 image data

I am currently facing an issue while trying to display images in base64 format within a RadListView component. Within the loop of the component, I have the following code snippet: let base64ImageSource = new ImageSource; base64ImageSource = fromBase64(re ...

Incorporating observables into an existing axios post request

Currently, I have an API using axios to send HTTP POST requests. These requests contain logs that are stored in a file. The entire log is sent at once when a user signs into the system. Now, I've been instructed to modify the code by incorporating Rx ...

Tips for sending back a response after a request (post | get) is made:

In the service, there is a variable that verifies if the user is authorized: get IsAuthorized():any{ return this.apiService.SendComand("GetFirstKassir"); } The SendCommand method is used to send requests (either as a post or get request): ApiServi ...

Exploring the mocking of document,hidden using Jasmine

Struggling to simulate document.hidden in an angular unit test, but facing issues. Tried the following solutions: spyOn(Document.prototype, <any>'hidden').and.returnValue(true); spyOn(Document, <any>'hidden').and.ret ...

Tips for leveraging multiple AWS Code Artifacts packages in a single project

Currently, I'm faced with a challenge while working on AWS CodeArtifact. My goal is to download three packages from the same domain. However, I have realized that I need to have three separate registries specified in my .npmrc file for each package in ...

Having trouble showing the fa-folders icon in Vuetify?

Utilizing both Vuetify and font-awesome icons has been a successful combination for my project. However, I am facing an issue where the 'fa-folders' icon is not displaying as expected: In the .ts file: import { library } from '@fortawesome/ ...

Ways to obtain a referrer URL in Angular 4

Seeking a way to obtain the referrer URL in Angular 4. For instance, if my Angular website is example.com and it is visited from another PHP page like domaintwo.com/checkout.php, how can I detect the referring URL (domaintwo.com/checkout.php) on my Angul ...

ESLint's no-unused-vars rule is triggered when Typescript object destructuring is employed

I'm encountering an issue with my Typescript code where I am destructuring an object to extract a partial object, but it's failing the linter check. Here is the problematic code snippet: async someFunction(username: string): Promise<UserDTO> ...

Utilize Angular to Transfer HTTP Array Data from a Service to a Component

As I work on developing an app with Angular, my current challenge involves a service that retrieves an Array of Data from an online source. My goal is to make this array accessible in other components but I'm facing difficulty in passing the data to t ...

Assess the equation twice using angular measurement

I am attempting to assess an expression that is originating from one component and being passed into another component. Here is the code snippet: Parent.component.ts parentData: any= { name: 'xyz', url: '/test?testid={{element["Te ...

Angular: Authorization Process for Instagram - Retrieving Access Token

Currently, I am in the process of developing an application that will showcase live feeds from Instagram, Twitter, Facebook, and YouTube based on a specific hashtag. Initially, my focus is on integrating Instagram, assuming it would be a straightforward t ...

The array contains data, yet the console is displaying a length of 0 for the array

I’m experiencing an issue with my code that involves a files array. Whenever I add a new file, it displays the incorrect length of the array. Strangely, if I use setTimeout to check the length, it shows the correct one. console.log('row.myDocuments ...

Issue with rendering of material icon

I'm having trouble properly rendering a material icon in my project. I've installed it correctly, but it's not showing up in the browser. Here are the steps I followed: npm install material-design-icons In my .angular-cli.json file, I mad ...

Tips for showing nested JSON data in a PrimeNG table within Angular version 7

I am struggling to display nested json data in a PrimeNG table. When I retrieve the data using an HTTP service, it appears as [object][object] when displayed directly in the table. What I want is to show the nested json data with keys and values separated ...

Add the JavaScript files to the components

I am working on integrating an admin template into my Angular2 project (version 2.1.0) which is already equipped with Bootstrap, jQuery, and jQuery plugins. Since there are numerous jQuery plugins and JS files involved, I am faced with the challenge of ho ...

Is it considered bad form to utilize nearly identical for loops in two separate instances within Angular 6?

I am working on creating two lists for a roster. The first list will display the current members of this year, while the second list will show if individuals have been excused for this year. After analyzing my code, I realized that I am using two identic ...