Retrieving information from the database and mapping it to an array

Currently in my Angular application, I have hardcoded values in an array and bound them to a dropdown list using the in-built control, which is functioning correctly. The current setup looks like this:

export class UserDetailsComponent implements OnInit {

constructor(private _userManagemement: UserManagementService){
}

userDetails : IUserDetails = {
 selectedValue: 'tim435'
 items: [
  {
    text: 'tim hoppins',
    value: 'tim435',
    id: 12
  },
  {
    text: 'andrew ramos',
    value: 'and71',
    id: 18
  },
  {
    text: 'jay ronne',
    value: 'jr214',
    id: 21
  }
 ]
 };

}

Now, my goal is to dynamically fetch details from the database instead of hardcoding them in the code. To achieve this, I have created an API and a method in the service that calls the endpoint like this:

export class UserManagementService {

  public getUserDetails() {
     return this.httpClient.get('endpoint');
  }

}

However, I am unsure of how to bind the data returned by the getUserDetails() method in the service to the items array of my userDetails object.

Answer №1

To customize the response according to your requirements, you can map it to the desired structure.

public fetchUserDetails(): Observable<IUserDetails> {
    return this.httpClient.get('api/user').pipe(map(response => ({
   items: response, selectedValue: response ? response[0]?.value : undefined
 })
}

Next, within your component, store the resulting UserDetails Observable as a variable at the component level.

userDetails$: Observable<IUserDetails> = userService.fetchUserDetails();

Finally, in your template, make use of userDetails$ | async to automatically subscribe/unsubscribe where needed.

<select>
    <option *ngFor="let userDetail of (userDetails$ | async)?.items" value="userDetail.value">
       {{ userDetail.text }}
    </option>
</select>

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 send parameters with the fetch API

After completing a task that involved converting code from Angular HttpClient to using fetch API, I encountered an issue with passing parameters. Below is the original code snippet before my modifications: let activeUrl = new URL(this.serverAddress); ...

Generate a new data structure by pairing keys with corresponding values from an existing

Imagine having a type named Foo type Foo = { a: string; b: number; c: boolean; } Now, I am looking to create a type for an object containing a key and a value of a designated type T. The goal is for the value's type to be automatically determin ...

Multiply elements in an array by using a recursive for loop algorithm

Currently, I am in the process of developing a program that involves multiplying elements in a 2D array with elements in subsequent rows. To accomplish this, I have implemented a recursive method that initially traverses each row of the 2D array, identif ...

Tips for utilizing angular pre-rendering alongside transloco?

After I prerender my Angular application, I am encountering an issue where the translation text is not visible when using Transloco. This is because it utilizes HTTP to fetch data from asset/i18n/en.json. Is there a way to implement prerendering with dyna ...

Aurelia TypeScript app experiencing compatibility issues with Safari version 7.1, runs smoothly on versions 8 onwards

Our team developed an application using the Aurelia framework that utilizes ES6 decorators. While the app works smoothly on Chrome, Firefox, and Safari versions 8 and above, it encounters difficulties on Safari 7.1. What steps should we take to resolve th ...

Angular 6 Universal does not pause for resolver completion

I recently completed the installation of Angular Universal start kit version 6 and designed my component within it. The main purpose of this component is to retrieve user information from an API upon loading and display it on the view. The issue I am faci ...

Need to Resend SMS Verification in Angular4 Firebase Phone Authentication? Here's How!

Currently, I am developing a project using angular 4 and ionic 3. One of the features in my project is implementing firebase phone authentication for the login page. While working on this, I encountered the need to add a functionality to resend OTP when ...

Testing Vue components with Typescript and Jest does not display the expected values in the HTML output

Recently, I decided to focus on Test-Driven Development (TDD) using Typescript, so I started a new Vue project with vue-cli. I specifically chose Vue3, Typescript, and Jest for this project. However, when I ran the unit test initially, it failed to execute ...

The error being thrown at line 538 in the module.js file is causing issues when using

I encountered an error in my Angular 4 project that says "module.js:538 throw err;". Can anyone provide insight on what this means? module.js:538 throw err; ^ Error: Cannot find module 'swagger-js-codegen' at Function.Module._resolveFilena ...

Storing a Vue/JS element reference in a constant using Typescript

In my template, I have one form element and one button element: <button type="submit" id="ms_sign_in_submit" ref="submitButton" class="btn btn-lg btn-primary w-100 mb-5"> </button> Wi ...

Align the headers of columns to the right in the AgGrid widget

Is there a way to align the column headers to the right in AgGrid without having to implement a custom header component? It seems like a lot of work for something that should be simple. You can see an example here: https://stackblitz.com/edit/angular-ag-g ...

Transforming a collection of nested lists into a numpy array

If you're thinking of flagging this question as a duplicate, take a moment to go through the entire post... I've got a collection of lists that resembles something like this... >>> print(list_of_lists) [[3, 3, 7, 8, 5], [9, 3, 3, 3, 3] ...

What is the method for defining a monkey patched class in a TypeScript declarations file?

Let's say there is a class called X: class X { constructor(); performAction(): void; } Now, we have another class named Y where we want to include an object of class X as a property: class Y { xProperty: X; } How do we go about defining ...

Unraveling JSON Arrays and Iterating Through Them in VB.NET

My current JSON data looks like this: { "TNS-API-KEY": "ABCD134EFG456HIJK678LMNOP", "docno": "35829", "idtns": "abc12345", "action": "6", "reason" ...

Steps to activate or deactivate a button in Angular 2 depending on required and non-required fields

I am looking to have the Save button activated when the Placeholder value is set to 'Optional'. If the value is set to 'Mandatory', then the Save button should be deactivated and only become active if I input a value for that field. He ...

Why is the 'as' keyword important in TypeScript?

class Superhero { name: string = '' } const superheroesList: Superhero[] = []; const superheroesList2 = [] as Superhero[]; As I was exploring TypeScript, I stumbled upon these two distinct methods of declaring an array. This got me thinking w ...

What is the best way to retrieve the parameter of ng2-file-upload using endback?

I am attempting to retrieve a parameter using PHP in order to save it into a folder. However, my code is not working as expected. Here is the code snippet: Using the Ionic framework this.uploader.onBeforeUploadItem = (item: any) => { this.uploader ...

Tips for understanding nested JSON or array data structure?

My data is stored in a constant called translations and it looks like this: { "item-0": { "_quote-translation": "translation Data", "_quote-translation-language": "English", "_quote-trans ...

Having trouble retrieving the file using the MS Graph API, however, it is successfully accessible through Graph Explorer

User B received an excel file shared from User A's Onedrive, whether it is in the personal folder or business OneDrive. Accessing it through regular means such as a link works fine for user B. Running the call in MS Graph Explorer produces the expect ...

The state may be modified, but the component remains unchanged

I've been tasked with implementing a feature on a specific website. The website has a function for asynchronously retrieving data (tickets), and I need to add a sorting option. The sorting process occurs on the server side, and when a user clicks a s ...