Unable to set intricate information to array variable in Angular 6

I have successfully implemented a method for retrieving data from an HTTP request, and it is functioning well, returning a complex list of data.

https://i.sstatic.net/Hxpz2.png

However, my concern arises when I try to assign the returned list to a variable. It seems that the assignment is not happening correctly, as the variable remains undefined in the .ts file and I am unable to loop through it.

https://i.sstatic.net/56EAh.png

Below is the Component code:

import { Component, OnInit } from '@angular/core';
import { ChatUserVM } from '../shared/models';
import { UserService } from '../shared/service/user.service';
@Component({
  selector: 'app-chat-footer',
  templateUrl: './chat-footer.component.html',
  styleUrls: ['./chat-footer.component.css'],
})
export class ChatFooterComponent implements OnInit { 
  friendList: ChatUserVM[] = []; 

  constructor(private userService: UserService) {  
  }

  ngOnInit() {
    this.getAllFriendsFromDatabase();
  }

  getAllFriendsFromDatabase() {
    this.userService.getUsers().subscribe(
      data => {
        this.friendList = data;
        console.log('DB usersss ---> ' + this.friendList);
      }
    );
  }
}

And here is the HTTP service code:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {ChatUserVM} from "../models";

@Injectable()

export class UserService {

  constructor(private http: HttpClient) { }

  getUsers() {      
    return this.http.get<ChatUserVM[]>('https://localhost:44346/api/chat/GetAllUsers');
  }
  
}

Answer №1

There seems to be a bug in the debugger here. It's having trouble with this. If you were to inspect the generated JavaScript, you would see the correct values. However, in this case, the debugger is interpreting this as window, which likely does not have a friendList field or property. This results in it displaying "undefined". That's why I prefer debugging the generated JavaScript over TypeScript code. I'm not saying you shouldn't debug TypeScript code, just keep in mind this potential issue.

Answer №2

The issue has been successfully resolved! It started working as expected after implementing the following changes.

 retrieveAllFriendsFromDatabase() {
    var that = this;
    this.userService.fetchUsers().subscribe(
      response => {
        that._moderatorList = response as ChatUserVM[];
        console.log('DB users ---> ' + that._moderatorList);
      }
    );
  }

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

Creating an RxJS observable stream from an event emitted by a child element in an Angular 2 component template

Currently incorporating Angular 2.0.0-rc.4 alongside RxJS 5.0.0-beta.6. In the midst of exploring various methods for generating observable streams from events, I find myself inundated with choices and would like to gather opinions. Recognizing that there ...

Encountered an issue with JSON serialization while using getServerSideProps in Next.js and TypeScript to retrieve products from the Stripe Payments API

Encountered Issue on Localhost Error: The error occurred while serializing .products returned from getServerSideProps in "/". Reason: JSON serialization cannot be performed on undefined. Please use null or exclude this value. Code Sample import ...

Creating a union type from an array that is not a literal (using `Object.keys` and `Array.map`)

Can a union be derived from a non-literal array? I attempted the following: const tokens = { "--prefix-apple": "apple", "--prefix-orange": "orange" }; const tokenNames = Object.keys(tokens).map(token => toke ...

What is the best way to send a search parameter to a URL?

In my asp.net core web api, I developed a method that generates an object with the string provided in the URL. I now have a search form that needs to pass this string to the URL and retrieve the objects containing it. Here is how I utilize the api: impo ...

The onChange event will not be triggered in an input component that is not intended to be uncontrolled

Could someone please assist me in understanding why the onChange event is not being triggered? I am customizing ChakraUI's Input component to retrieve a value from localStorage if it exists. The component successfully retrieves the value from localS ...

The issue with IONIC/Angular lies in its inability to properly render the JSON data retrieved

I have recently started learning IONIC/Angular and Javascript, although I do have some background in other programming languages. The issue I'm currently facing is related to fetching JSON data from an external API (I've created the API with Stra ...

Analyzing a string using an alternative character

I want to convert the string "451:45" into a proper number. The desired output is 451.45. Any help would be appreciated! ...

Does moment/moment-timezone have a feature that allows for the conversion of a timezone name into a more easily comprehendible format?

Consider this example project where a timezone name needs to be converted to a more readable format. For instance: input: America/Los_Angeles output: America Los Angeles While "America/Los_Angeles" may seem human-readable, the requirement is to convert ...

Utilize TypeScript to import a JSON file

I am trying to incorporate a JSON file using TypeScript, which contains data about different regions in Italy along with their respective capitals. Here is a snippet of the data: { "italia": [ { "regione": "Abruzzo", "capoluoghi": [ ...

The "if(x in obj)" statement in Typescript does not properly narrow down my custom Record

I am struggling with a code snippet where I am trying to check if a string exists in my custom record using the if(x in obj) guard statement, but it seems to not be working as expected. Below is the sample code snippet that is throwing an error: type Ans ...

Tips for preventing event propagation while clicking on a swiper.js image next/prev button within a bootstrap card

I have integrated ngx-swiper-wrapper within a bootstrap card as shown below, with a routerlink at the top. When I click anywhere on the card, it successfully routes to the designated page. However, I am facing an issue where I want to prevent routing if a ...

React Typescript is causing issues with the paths not functioning properly

Looking to simplify my import paths and remove the need for deeply nested paths. Currently working with React and TypeScript, I made adjustments to my tsConfig file like so: { "compilerOptions": { "baseUrl": "src", & ...

When subscribing to an Observable of type number or string (union type), NaN values are returned for string inputs

Within a component, I have a public member that is defined as follows: public docId$: Observable<number | string>; This means that the document ID can either be an integer or a string. Upon initializing in ngOnInit, I have the following code snippe ...

How can I organize an array in JavaScript by date for presentation on a webpage?

Check out this code snippet: list.component.ts const data1 = [ { dateStart: "2020-02-14 00:00:01", name: 'Server1' }, { dateStart: "2020-02-13 14:00:01", name: 'Server1' }, ...

Switch the MatSlideToggle within an Angular 8 component

I seem to be encountering a persistent error: "ERROR TypeError: Cannot set property 'checked' of undefined" Take a look at my code snippet from test.component.ts: import { Component, OnInit, ViewChild } from '@angular/core'; import { ...

What is the best way to include documentation for custom components using jsDoc?

Within my Vuejs inline template components, we typically register the component in a javascript file and define its template in html. An example of such a component is shown below: Vue.component('compare-benefits', { data() { // By return ...

Set a value to the field name within a variable in TypeScript

Can anyone help me with this problem? type A { f1: string; f2; string; } I have a variable that holds the name of a field: let fieldName: string = "f2"; I want to create an object using the fieldName: {"content of fieldName": "sdf"} Any suggestio ...

There was an issue: Control with the name 'name' could not be located

Whenever I submit the form and try to go back, an error pops up saying "ERROR Error: Cannot find control with the name: 'name'". I'm not sure what I might be missing. Do I need to include additional checks? Below is my HTML file: <div ...

Implement a delay for a specific function and try again if the delay expires

In my TypeScript code, I am utilizing two fetch calls - one to retrieve an access token and the other to make the actual API call. I am looking to implement a 1-second timeout for the second API call. In the event of a timeout, a retry should be attempted ...

Tips for integrating TypeScript with Vue.js and Single File Components

After extensive searching online, I have struggled to find a straightforward and up-to-date example of setting up Vue.js with TypeScript. The typical tutorials out there either are outdated or rely on specific configurations that don't apply universal ...