Angular: Utilizing httpClient to retrieve an object map and passing it as a return value in a function

I have a basic Angular application that retrieves data from a Spring-Boot backend.

export class UserDto {

  constructor(
    public login: string,
    public password: string,
  ) {
  }
}

export class AuthService {
   private url = '....';

getUser() {
   return this.http.get<UserDto[]>(this.url);
  }
}

In my component, I have a function that creates a map of values:

constructor(private auth: AuthService){}

private getMapOfUsers() {
    const userMap: Map<string, string> = new Map<string, string>();
    this.auth.getUser().subscribe(res => {
      res.map(item => {
          userMap.set(item.login, item.password);
        }
      );
    });
    return userMap;
  }

When I call:

getLoginData() {
    console.log(this.getMapOfUsers());
  }

The console displays the result:

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

The login from UserDto appears crossed out in red

Even though I see objects in "Entries", the size of the map is displayed as 0. I am unable to retrieve the actual size or content of the map.

getLoginData() {
    console.log(this.getMapOfUsers().size);  // result = 0
  }

How can I resolve this issue so that I can successfully map these objects and access the password using the login as the key?

Answer №1

The issue lies within this section of the code:

private retrieveUserMap() {
    const userListMap: Map<string, string> = new Map<string, string>();
    this.auth.getUser().subscribe(res => {
      res.map(item => {
          userListMap.set(item.login, item.password);
        }
      );
    });
    return userListMap;
  }

Since the code within the subscription runs asynchronously, there's a possibility that you are returning userListMap before it is fully populated.

There are several approaches to address this issue. One recommended method is to directly bind userListMap to your template using the async pipe. Alternatively, you can use an async/await pattern to wait for the result, but it can lead to complex code. For more insights on async/await with observables, refer here.

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

Encountering difficulties resolving the dependency tree for an angular-ionic project

Node version: v16.3.0 ng version: 12.1.0 Currently working on an Angular-Ionic 5 project Encountered an error while running the npm install commandhttps://i.sstatic.net/nYOJc.png 2. Also tried running npm install --force but faced a different error h ...

How can I determine if any of the values in the array (both previous and current) are identical?

I am facing a challenge with 3 input fields that could potentially have the same values, but I need to ensure uniqueness for each field. {productFormData.Roles.map((role: string, index: number) => { return ( <div className={`form-group in ...

What is the best approach to creating a Typescript library that offers maximal compatibility for a wide range

My Vision I am aiming to develop a versatile library that can cater to both JavaScript and TypeScript developers for frontend applications, excluding Node.js. This means allowing JavaScript developers to utilize the library as inline script using <scri ...

RXJS - Implementing a conditional logic in the switchMap operator to determine if it's the first

In my service's http fetch method, there is a parameter called "showLoadingSpinner". When this parameter is set to false, the HttpContext DISABLE_LOADER_FOR_REQUEST = true will be set. I would like to set showLoadingSpinner to false for every subsequ ...

The error message "Unexpected token (13:22) found in docs/file.js while parsing" was encountered in IONIC2

I have integrated a component named Swiper-Angular2 into my IONIC 2 project, but I encountered an unusual error message that reads: SyntaxError: docs/file.js: Unexpected token (13:22) while parsing file: docs/file.js Here is a snippet of my code: page ...

Unable to bind input data with interface in Ionic 4 – issues persist

I am working with an interface in Ionic that looks like this: // mydata.model.ts export interface Mydata{ id: string; name: string; date: string } To add new data to the backend, I am binding my data within my component using <ion-input> a ...

ng2-dragula error: issues with setting options and dropping version

It seems that version 1.5.0 supports this.dragulaService.setOptions, while version 2.1.1 does not, and vice versa with this.dragulaService.drop subscribe where version 2.1.1 supports it but 1.5.0 does not. Check out the Stackblitz Fork for version 1.5.0 ...

Click on a kendo-chip in Angular to copy its content

Can someone assist me in copying the content within a Kendo Chip when clicked in an Angular application? Your help is greatly appreciated. View image here ...

TypeScript - Converting into individual compiled files

Currently, I am working on a project that consists of lengthy source files. While this is advantageous for imports, it poses challenges in terms of maintenance. For instance: /main/core.ts export type Foo { ... } export interface Bar { ... } export cla ...

"Encountered a runtime error while trying to execute the doubleClick() function using Pro

Encountering the following issue: "WebDriverError: Unable to convert: Error 404: Not found" while running a test with protractor: browser.actions().doubleClick(elem).perform(); or browser.actions().click(elem).click(elem).perform(); Uncertain of t ...

Does Nativescript have a feature similar to "Hydration"?

It's been said that Phonegap offers an exciting feature called Hydration, which can lead to rapid and efficient deployments when combined with CD. Is it feasible to incorporate this concept into a Nativescript application? While I may not be well-ve ...

Sending an email using Angular is a straightforward process that involves utilizing the built

I need help figuring out how to code a function in Angular or TypeScript that will open Gmail when a specific email address is clicked. I've tried different methods but haven't been successful so far. ...

Issue: Unable to find 'rxjs/add/operator/map'

In the app.module.ts file, I have attempted to import the map in various projects and it worked smoothly. However, in this particular project, it seems to be causing some issues. import { BrowserModule } from '@angular/platform-browser'; ...

Tips for finding the displayRows paragraph within the MUI table pagination, nestled between the preceding and succeeding page buttons

Incorporating a Material-UI table pagination component into my React application, I am striving to position the text that indicates the current range of rows between the two action buttons (previous and next). <TablePagination ...

Setting up angular-cli project for rc5- Step by step guide

Trying to integrate angular-cli with angular 2 rc5 but facing challenges: The issue of 'Promise' not being found After attempting to install 'npm install -g angular-cli@webpack', typings did not get installed, resulting in WebStorm un ...

Preserving hyperlinks while transferring text from an HTML element using JavaScript

I'm struggling to preserve links from HTML elements while copying rich text, but have been unable to achieve it despite numerous attempts. The following code represents my best effort so far, however it only copies text without maintaining the links ...

Determining the type of a utilized generic function

When working with TypeScript, it is possible to determine the type of a function by using the following method: function exampleFunc(param: number) {} type ExampleFuncType = typeof exampleFunc; // RESULT: (param: number) => void If the function is gen ...

Expanding the capability of a function by inheriting properties of either type any or unknown

Can you explain why the values of P1 and P2 are different in these type definitions? type P1 = (() => 22) extends {[k:string]:any} ? 1:2 //`P1 == 1` type P2 = (() => 22) extends {[k:string]:unknown} ? 1:2 //`P2 == 2` ...

Searching through a json object using typescript

While attempting to retrieve JSON data from a URL, I encountered a particular issue. The problem lies in the fact that each row in the Datarows array contains 5 rows, each row consisting of 47 cells. Out of these 47 cells in each row, I am specifically in ...

Mastering the Type Checking of React Select's onChange Event Handler

Currently, I am in the process of building a design system based on React TypeScript. For the Dropdown component, I have opted to utilize React Select to handle most of its functionality. To customize the Dropdown component, I have created a wrapper compo ...