The API request does not provide randomized results and does not show any display

I am facing an issue with a button that is supposed to fetch a random user from an API. When I retrieve all the users, the information is displayed correctly. However, when I try to select a user at random, it does not work as expected. Also, it seems to always show the same user instead of randomizing each time. Error message:

ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'John Doe'. NgFor only supports binding to Iterables such as Arrays.
service file:

randomNumber = Math.floor(Math.random() * 10)
random(){
   return this._httpClient.get(`${this.placeholderApi}/users/${this.randomNumber}`)
}

html file:

<div *ngFor="let user of users" class="container emp-profile">
   <h5>
      {{user.name}}
   </h5>

users.component.ts

export class UsersComponent implements OnInit {
  users;

  getRandomUser() {
    this.clearUsers()
    this._dataService.random().subscribe(
      result => this.users = result
    )
  }

  clearUsers() {
    this.users = null 
  }

Answer №1

It is important to note that when fetching a random user, Angular may encounter an error with *ngFor since only one object is retrieved. To address this, the simplest solution is to push the received user into the users array without modifying the template.

Furthermore, ensure to clear the array by initializing it as empty after each retrieval to prevent Angular from raising concerns about attempting to push to undefined. I personally find it helpful to always reset an array by setting it as empty.

To implement these changes:

export class UsersComponent implements OnInit {
  users = [];

  getRandomUser() {
    this.users = [];
    this._dataService.random().subscribe(
      result => this.users.push(result)
      // alternatively, set this.users = [result] to avoid undefined errors
    )
  }

By following these adjustments, your users maintains its structure as an array!

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

How to showcase an image with Angular 2?

Just starting out with Angular 2 and ran into an issue while trying to display an image using a relative path. <img src="./../images/publicVideo1.PNG"> Unfortunately, I encountered the following error: null:1 GET http://localhost:4200/null 404 (No ...

Troubleshooting issue of incorporating hintText in a TextField within a create-react-app-with-typescript

After recently downloading, installing, and running the create-react-app-with-typescript, I have been exploring different components. My latest experiment involved adding a TextField with hintText using the following code: import TextField from 'mate ...

Troubleshooting problem with Angular HttpClient when invoking Bing Maps Locations REST APIs

Currently, I have successfully implemented a Bing Maps call using Angular 4 Http service: this.http.get("{absolute URL of Bing Maps REST Locations, with options and key}") Now, I am trying to transition this call to use the newer HttpClient service in An ...

Issue: In an Angular electron app, a ReferenceError is thrown indicating that 'cv' is

I have been working on a face detection app using OpenCv.js within an Angular electron application. To implement this, I decided to utilize the ng-open-cv module from npm modules. However, when attempting to inject the NgOpenCVService into the constructor ...

What is causing the Typescript compiler to interpret an element in a string array as the type 'never'?

My Typescript function compiled without issue in version 3.5.3, but after updating to 3.8.3, it now throws a confusing error during compilation. import { isNumber, toInteger, padNumber } from './math'; parse(value: string): NgbDateStruct { if ...

Neglecting to inquire with OpenLibrary

I'm looking to create a query for OpenLibrary's RESTful API that will achieve the following: Filter the book list based on the first five characters of the title Retrieve the book's title, author, publication date, description, and a link ...

Establishing the data type for the state coming from the API

Whenever I try to add a new API response to the status, it shows as undefined. I need to filter out the incoming data from randomcocktail and then put it to use. Random.tsx import { useState, useEffect } from "react"; import { CocktailType } ...

Ways to link information from one entity to another

Currently, I am utilizing the TMDB API to showcase movies along with their respective genres. In my code, I have two objects where I retrieve details for movies and genres as shown below: listTrendingMovies() { this.listMediaService.listTrendingMovie ...

I am encountering some difficulties in the installation process of Angular CLI

Encountering an error trying to install angular cli despite updating both node and npm. https://i.stack.imgur.com/SpkNU.jpg ...

The JSX element 'SubscribeCard' does not contain any construct or call signatures

I'm looking to implement the react-subscribe-card module for handling email subscriptions in my react.js project. Below is the code snippet from my popup.tsx file: import React from "react"; import SubscribeCard from "react-subscribe-c ...

Why is it that TypeScript does not issue any complaints concerning specific variables which are undefined?

I have the following example: class Relative { constructor(public fullName : string) { } greet() { return "Hello, my name is " + fullName; } } let relative : Relative = new Relative("John"); console.log(relative.greet()); Under certain circum ...

Steps for passing a JSON object as a PathVariable in a Spring controller

Currently, I am in the process of developing a spring application using AngularJS. My goal is to pass a JSON object as a @PathVariable to the spring controller. However, with my existing code, I am facing an issue where when attempting to pass the JSON obj ...

Creating a dynamic JSON data object with GSON库

I'm running into some issues with GSON when trying to parse my API response JSON. The response from my API includes a status code, message, and a data object. Unfortunately, I'm struggling to properly handle this with GSON. For instance, the A ...

Resolving conflict between a user-defined class name and a built-in class name

I am creating a TypeScript Map class that utilizes the built-in Map class along with generics. The problem arises when both classes have the same name. Is there a way to import the built-in Map using explicit namespace, similar to how it's done in Jav ...

Encountered Runtime Issue of TypeError: undefined cannot be iterated (unable to access property Symbol(Symbol.iterator))

I've been working on a multiselect feature in my Next.js project, utilizing states and setting them accordingly. However, I keep encountering this specific error: https://i.stack.imgur.com/m8zuP.png whenever I click on this: https://i.stack.imgur.c ...

Having trouble retrieving the Angular CLI version even after ensuring all the necessary requirements are installed?

I am facing challenges with using the Angular CLI. I have successfully installed Node, NPM, and Angular, as confirmed by running the which command in the terminal showing their locations in /user/local/bin. The current version of my node.js is v11.8.0. T ...

Ways to implement distinct values for model and input field in Angular 5

I'm currently working on an Angular 5 application and I have a requirement to format an input field with thousand separators (spaces). However, the model I am using only allows numbers without spaces. Since my application is already fully developed, ...

Unable to navigate using react-router after logging out without a page refresh

In my logout approach, everything seems to work fine - there are no errors in the console, localHistory is cleared successfully, but for some reason it cannot navigate to the login page without refreshing the current page. const handleLogout = () => { ...

Execute a function that handles errors

I have a specific element that I would like to display in the event of an error while executing a graphql query (using Apollo's onError): export const ErrorContainer: React.FunctionComponent = () => { console.log('running container') ...

Troubleshooting issue with Angular-CLI and Cordova plugin integration

While attempting to build an Angular 4 app using ng-build, I encountered an error when trying to access device.uuid: /navigation.component.ts (14,5): Cannot find name 'device'. Every plugin referenced in TS files is triggering this error. I a ...