Show a roster of individuals by inputting values that will populate the list with their names

I'm attempting to showcase a list of users by taking the value from an input and using it as a parameter in a get() method. After receiving the response from the get() method, I am pushing it into an object and then trying to display this object in the template.

My objective was:

  1. Search for a user.
  2. Display this specific user.
  3. Search for another user.
  4. Display both the new user and the initial one together.

However, the template is generating an error:

{ "_isScalar": false, "source": { "_isScalar": false, "source": { "_isScalar": false, "source": { "_isScalar": true, "value": { "url": "http://localhost:3000/users", "body": null, "reportProgress": false, "withCredentials": false, "responseType": "json", "method": "GET", "headers": { "normalizedNames": {}, "lazyUpdate": null, "headers": {} }, "params": { "updates": [ { "param": "user", "value": "Teste", "op": "s" } ], "cloneFrom": null, "encoder": {}, "map": {} }, "urlWithParams": "http://localhost:3000/users?user=Teste" } }, "operator": { "concurrent": 1 } }, "operator": {} }, "operator": {} }

Here's my component.ts code:

import { HttpClient, HttpParams } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-info',
  templateUrl: './info.component.html',
  styleUrls: ['./info.component.scss']
})
export class InfoComponent implements OnInit {
  public buscar: string;
  users: any;
  private readonly url = 'http://localhost:3000/users';
  select: any;
  usuario = [
    {
      user: ''
    }
  ];

  constructor(private http: HttpClient) { }

  ngOnInit() {
    this.users = this.http.get(this.url);
  }

  getDados(event) {
    if (event.keyCode === 13) {
      const params = new HttpParams().set('user', this.buscar);
      this.select = this.http.get(this.url, { params });
    }

    this.usuario.push({
      user: this.select
    });
  }
}

And here's my component.html code:

<igx-input-group type="search" class="search">
  <igx-prefix>
    <igx-icon>search</igx-icon>
  </igx-prefix>
  <input #search igxInput placeholder="Buscar" (keydown)="getDados($event)" [(ngModel)]="buscar">
  <igx-suffix *ngIf="search.value.length > 0" (click)="searchContact = null">
    <igx-icon>clear</igx-icon>
  </igx-suffix>
</igx-input-group>

<div class="list-sample">
  <igx-list>
    <igx-list-item isHeader="true">Users</igx-list-item>
    <igx-list-item #item *ngFor="let users of users | async">
      <div class="item-container">
        <div class="contact">
          <div  class="contact__info">
            <span class="id">{{users.id}} </span>
            <span class="user">{{users.user}}</span>
          </div>
        </div>
      </div>
    </igx-list-item>
  </igx-list>
</div>
<p *ngFor="let usuario of usuario">{{ usuario.user | json }}</p>

Any kind individual willing to assist would be greatly appreciated.

Answer №1

Today, I finally found a resolution to my issue. Although, I'm unsure if this is an optimal fix. Nonetheless, I've decided to share the modifications I made in my code in case it proves useful to someone in the future.

Below are the alterations I implemented in my component.ts file:

import { HttpClient, HttpParams } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { Observable, throwError, } from 'rxjs';
import { map, catchError } from 'rxjs/operators';

@Component({
  selector: 'app-info',
  templateUrl: './info.component.html',
  styleUrls: ['./info.component.scss']
})
export class InfoComponent implements OnInit {
  public search: string;
  users: Observable<any>;
  private readonly url = 'http://localhost:3000/users';
  select: {id: number; user: string} [];
  list: { user: string } [];
  displayedUser: { user: string } [];

  constructor(private http: HttpClient) {
    this.displayedUser = new Array<any>();
    this.list = new Array<any>();
  }

  ngOnInit() {
    this.getUsers();
  }

  getUsers() {
    this.http.get<{ id: number; user: string; }[]>(this.url)
    .pipe(
      map(data => {
        return data.map(el => ({ id: el.id, user: el.user }));
      }),
      catchError(error => {
        return throwError('An error occurred!');
      })
    )
    .subscribe((transformedData: { id: number, user: string }[]) => {
      this.select = transformedData;
    });
  }

  fetchData(event) {
    if (event.keyCode === 13) {
      const params = new HttpParams().set('user', this.search);

      this.http.get<{ user: string; }[]>(this.url, { params })
      .pipe(
        map(data => {
          return data.map(el => ({ user: el.user }));
        }),
        catchError(error => {
          return throwError('An error occurred!');
        })
      )
      .subscribe((transformedData: { user: string }[]) => {
        this.list = transformedData;
        console.log(this.list[0].user);
        this.displayedUser.push({
          user: this.list[0].user
        });
        console.log(this.displayedUser);
      });
    }
  }
}

Feel free to provide any feedback on this solution, and if you have a better alternative, please share it. Thank you.

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

Switch from Gulp-TSLint to Gulp-ESLint for enhanced code analysis!

I am currently in the process of updating a Gulp task that uses gulp-tslint to now use gulp-eslint. The code snippet below outlines the changes I need to make: const { src } = require('gulp'); const config = require('./config'); const ...

Obtaining a binary value in the switch component of materialize framework with Typescript

Is there a way in Typescript to assign a value of 1 when a checkbox is checked and 0 otherwise? I am working on a project that uses the materialize framework. Below is the code snippet in question: <div class='switch'> <label&g ...

What is the best way to conceal a specific list item in an Angular 2 template?

I need help figuring out how to hide a selected list item that has been added to another list. I want the added item to be hidden from view in the original list. <div class="countries-list"> <span class="countries-list__header">{{'G ...

Testing Angular 2's IF condition with unit tests

I just started learning about unit testing and I am currently working on testing the if condition in the code snippet below: hide() { this.count --; if (this.count === 0) { this.loaderIs = false; } } My goal is to ...

Angular HTTP client fails to communicate with Spring controller

Encountered a peculiar issue in my Angular application where the HttpClient fails to communicate effectively with the Spring Controller. Despite configuring proper endpoints and methods in the Spring Controller, the Angular service using HttpClient doesn&a ...

What steps can I take to have TypeScript limit the type of an array based on filter inference?

Here's a handy function that always returns an array of strings: (arr: (string | undefined)[]): string[] => arr.filter(item => item !== undefined); Check it out here However, TypeScript may not compile this code as expected due to its inferenc ...

Steering clear of the generic Function type in React with TypeScript

Can anyone help me find a guideline that prohibits the use of "Function" as a type? myMethod: Function; I have searched but couldn't locate any information on this. Appreciate any suggestions :) ...

Is there a way to prevent the leaderboard from resetting each time I restart my client?

Is it possible to prevent the leaderboard from resetting every time I restart my client? You can see an example here: https://i.stack.imgur.com/2nEPw.png Please disregard the "undefined" error, I will correct it. In the current setup, the leaderboard onl ...

Customizing the renderInput of the Material UI DatePicker

Recently I integrated material-ui into my React project with TypeScript. I implemented the following code based on the example provided on the official website. import AdapterDateFns from '@mui/lab/AdapterDateFns'; import DatePicker from '@m ...

How can I update the image source using Angular?

<div class="float-right"> <span class="language dashboard" data-toggle="dropdown"> <img class="current" src="us-flag.png" /> </span> <div class="dropdown dashboar ...

In Angular 11, the error message "Type 'Object' cannot be assigned to type 'NgIterable<any> | null | undefined'" is appearing

Struggling to grasp the concepts of Angular and TypeScript for the first time, particularly puzzled by why this code snippet is not considered valid! http.service.ts export class HttpService { constructor(private http: HttpClient) { } getBeer() { ...

React Redux not properly handling text input updates when onChange event is triggered

I have come across similar inquiries, but they haven't provided the solution I need. Currently, I am working on a React project where I am integrating redux. This is how my index.js looks: import React from "react"; import ReactDOM from "react-dom"; ...

A guide to seamlessly uploading files to s3 using nextjs, node, and typescript

I've been struggling to successfully upload a basic image to s3 using ts/nextjs/node. Despite having all the necessary credentials and code in place, I'm still unable to get it working. Can someone please provide clear instructions on how to achi ...

Updating FontAwesome icon in Angular 10

I have successfully configured and implemented FontAwasome Pro in my Angular 10 project. <div class="update-split" [class]="testClass"><fa-icon [icon]="['fad', 'sync-alt']"></fa-icon></ ...

Obtaining the IP address upon page load in Angular 4: A step-by-step guide

In the midst of my Angular4 project, I'm on a mission to fetch the system IP address upon page load and send it over to the API for storage in a MSSQL database. However, each time the page loads, two rows are inserted and the IP address is coming up a ...

Hierarchy-based state forwarding within React components

As I embark on the journey of learning Typescript+React in a professional environment, transitioning from working with technologies like CoffeeScript, Backbone, and Marionettejs, a question arises regarding the best approach to managing hierarchical views ...

The ngx-image-cropper in Angular only necessitates a button click, making the default cropper unnecessary

Currently, the image is cropped by default when loaded, but I would like the crop to only occur when the crop button is clicked. I tried searching on Google and found autoCrop:false, but I am unsure where to place it in the code. Below is the HTML code: ...

When utilizing two-way binding in reactive forms, the mat-select component may fail to show the selected value

Here is the code for a Reactive Form: createInputForm() { console.log('creating form'); this.instituteForm = this.formBuilder.group( { address: [this.instituteData.address, Validators.required], city: [this.institu ...

Retrieve the duplicated items from an array by comparing two specific properties in JavaScript

I need assistance in identifying and retrieving duplicate objects within an array that share similarities in 2 specific properties. Consider the object structure below: let arry = [ {Level: "A-1", Status: "approved"}, {Level: &q ...

Looking for guidance on integrating REST API consumption features into Ionic Framework 3.x?

It's been a long time since I last used the ionic framework. The version I worked with was 1, where every page created with Ionic Creator had its own controller for adding JavaScript code to consume my REST framework. Now that I've downloaded th ...