Patience is key as we anticipate the promise's response to fill out the

Hello, I am currently developing an angular/typescript application and I have been researching about promises. However, I am still struggling to fully understand it. I would greatly appreciate your assistance.

I have a function called getUserById() which returns user information, as well as another function called getAttributeByUserId(). My goal is to populate a form using data from both functions, but the variables in getAttribute are showing up as undefined. Below is my code snippet:

Angular / Typescript

getUserById(userId, modalContent) {
  console.log('get user by id ' + userId);
  const config = AppConfiguration.CONFIG_GET_USERS_BY_ID;
  config.user_id = userId;
  const date = new Date();
  this._httpService.CountUsers().post(config).subscribe((data: any) => {
    console.log('resultado al obtener usuario editado ' + data[0].user_id);
    this.userForm.patchValue({'firstName': data[0].firstname});
    this.userForm.patchValue({'secondName': data[0].secondname});
    this.userForm.patchValue({'lastName': data[0].lastname});
    this.userForm.patchValue({'mothersLastName': data[0].motherslastname});
    this.userForm.patchValue({'birthDay': {
      date: {
        year: data[0].birthday.substring(0, 4),
        month: data[0].birthday.substring(5, 7),
        day: data[0].birthday.substring(8, 10)}
    }});
    this.userForm.patchValue({'roleId': data[0].role_id});
    this.userForm.patchValue({'email': data[0].email});
    this.userForm.patchValue({'userId': data[0].user_id});
    this.open(modalContent);
    // this.open(modalContent);
  });
}

getAttributeByUserId(userId: number) {
  const config = AppConfiguration.CONFIG_GET_ATTRIBUTE_BY_ID;
  config.user_id = userId;
  this._httpService.CountUsers().post(config).subscribe((data: any) => {
    this.attributes = data;
  });
}

In order to retrieve the data, I need to call getAttributeByUserId within getUserById.

Answer №1

Upon reviewing your response, the clarity of your query has improved. It is necessary to provide an observable that can be subscribed to from the getAttributeByUserId method. If you wish to add the returned value to the attributes, you can achieve this within the method using tap for executing code without modifying the result before the subscribe callback, or allow the caller to handle it in the subscribe callback. Personally, I opted for the former approach.

Furthermore, a crucial suggestion for your TypeScript / Angular development journey: Embrace strong typing. This practice can prevent runtime errors in the future, which are harder to identify or rectify. I assume there is an interface or class named Attribute below. If not, I recommend utilizing an interface (a common practice for data structures obtained from HTTP requests).

import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';


getUserById(userId, modalContent) {
  console.log('get user by id ' + userId);
  const config = AppConfiguration.CONFIG_GET_USERS_BY_ID;
  config.user_id = userId;
  const date = new Date();
  this._httpService.CountUsers().post(config).subscribe((data: any) => {
    console.log('resultado al obtener usuario editado ' + data[0].user_id);
    this.userForm.patchValue({'firstName': data[0].firstname});
    this.userForm.patchValue({'secondName': data[0].secondname});
    this.userForm.patchValue({'lastName': data[0].lastname});
    this.userForm.patchValue({'mothersLastName': data[0].motherslastname});
    this.userForm.patchValue({'birthDay': {
      date: {
        year: data[0].birthday.substring(0, 4),
        month: data[0].birthday.substring(5, 7),
        day: data[0].birthday.substring(8, 10)}
    }});
    this.userForm.patchValue({'roleId': data[0].role_id});
    this.userForm.patchValue({'email': data[0].email});
    this.userForm.patchValue({'userId': data[0].user_id});

    this.getAttributeByUserId(userId).subscribe((attributes) => {
      this.open(modalContent);
    });
  });
}

getAttributeByUserId(userId: number) : Observable<Attribute[]> {
  const config = AppConfiguration.CONFIG_GET_ATTRIBUTE_BY_ID;
  config.user_id = userId;
  return this._httpService.CountUsers().post<Attribute[]>(config).pipe(tap((data) => {
    this.attributes = data;
  }));
}

Answer №2

i made adjustments to the functions

getUserInformation(userId, modalContent) {
console.log('retrieving user information for ID ' + userId);
const config = AppConfiguration.CONFIG_GET_USERS_BY_ID;
config.user_id = userId;
const date = new Date();
this._httpService.CountUsers().post(config).subscribe((data: any) => {
  console.log('result after retrieving edited user ' + data[0].user_id);
  this.userForm.patchValue({'firstName': data[0].firstname});
  this.userForm.patchValue({'secondName': data[0].secondname});
  this.userForm.patchValue({'lastName': data[0].lastname});
  this.userForm.patchValue({'mothersLastName': data[0].motherslastname});
  this.userForm.patchValue({'birthDay': {
    date: {
        year: data[0].birthday.substring(0, 4),
        month: data[0].birthday.substring(5, 7),
        day: data[0].birthday.substring(8, 10)}
    }});
  this.userForm.patchValue({'roleId': data[0].role_id});
  this.userForm.patchValue({'email': data[0].email});
  this.userForm.patchValue({'userId': data[0].user_id});
  this.getAttributeByUserId(data[0].user_id).then((response) => {
    console.log('response from attribute web service' + JSON.stringify(response));
    this.open(modalContent);
  });
  // this.open(modalContent);
});

}

getAttributeByUserId(userId: number) {
const config = AppConfiguration.CONFIG_GET_ATTRIBUTE_BY_ID;
config.user_id = userId;
this._httpService.CountUsers().post(config).subscribe((data: any) => {
  this.attributes = data;
});
return Promise.resolve(this.attributes);

}

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

Is there a way to create a typesafe Map in TypeScript with a key and value both being of the same generic type X?

The desired outcome should be as follows: const newObj: ??? = { [Fruit<Apple>]: Taste<Apple>, [Fruit<Banana>]: Taste<Banana>, } const selectedKey: Fruit<Apple> = ...; newObj[selectedKey] // should only return Taste<A ...

Ensuring an integer value is selected in Angular

<form [formGroup]="form"> <select name="area_id" formControlName="area_id"> <option value="1">Value A</option> <option value="2">Value B</option> <option value="3">Value C</option> ...

Creating a new section in an Angular 2 project can be achieved by implementing an onclick function that is

Whenever I click the new button, a section with 3 fields should appear. However, even though I am not receiving any errors, I can't seem to figure out what I'm doing wrong. Click here for an example Here is the HTML: <form *ngFor="let ...

React Typescript Context state isn't refreshing properly

Struggling to modify my context state, I feel like I'm overlooking something as I've worked with context in the past. The challenge lies in changing the 'isOpen' property within the context. You can view my code here: CodeSand **app.ts ...

Node.JS retrieves information from MongoDB when a GET request is made

My goal is to send data from a MongoDB server to the client upon receiving a GET request. I am utilizing an express server and aiming to return all the documents in a specific collection when the GET request is made. Working with MongoDB's asynchrono ...

What is the best way to verify the input of a TextField element?

When I visited the Material UI Components documentation for TextField, I was hoping to find an example of validation in action. Unfortunately, all they showed was the appearance of the invalid TextField without any insight into the actual validation code i ...

Setting up TypeScript to function with Webpack's resolve.modules

Imagine having a webpack configuration that looks like this: resolve: { extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'], modules: ['my_modules', 'node_modules'], }, You have a ...

How to Retrieve Files Using Angular 6 from a RESTful API

A challenge I am facing is with my REST API where I have uploaded a PDF file. I am now trying to enable my Angular app to download the file when a user clicks on a button through the web browser. However, I am encountering an HttpErrorResponse with the err ...

What is the best way to display HTML file references in TypeScript files using VSCode when working with Angular templates?

Did you know that you have the option to enable specific settings in VSCode in order to view references within the editor? Take a look at the codes below: "typescript.implementationsCodeLens.enabled": true, "javascript.referencesCodeLens.enabled": true I ...

FabricJS Canvas with a React DropDown Feature

While I have successfully created a TextBox on FabricJS Canvas, creating a Dropdown component has proven to be a challenge. The fabric.Textbox method allows for easy creation of text boxes, but no such built-in method exists for dropdowns in FabricJS. If y ...

What is the best way to use an Observable to interrogate a fork/join operation?

I have a forkjoin set up to check for the presence of a person in two different data stores. If the person is not found in either store, I want to perform a delete action which should return true if successful, and false otherwise. However, my current impl ...

What is the best way to update the color of a label in a Mantine component?

When using the Mantine library, defining a checkbox is done like this: <Checkbox value="react" label="React"/> While it's possible to change the color of the checkbox itself, figuring out how to change the color of the label ...

How can I display the current index within an Angular component?

Currently, I am faced with a situation where an Angular component is being replaced for each element in an array: <app-doc-item *ngFor="let docFeatureEl of docFeatures; let i = index"; [documentFeature]="docFeatureEl" > ...

Ways to verify that the Google Analytics code is functioning properly within an Angular 2 application

I'm just getting started with Google Analytics and I'm attempting to integrate it into my Angular 2 project. Here's how I've set it up: app.component.ts import { Component } from '@angular/core'; import {Router, NavigationEn ...

What is the best way to delegate the anonymous function logic contained within the subscribe() method?

Imagine you have a code block similar to this: constructor(private _http: HttpClient) { this.fetchUsers(5); } employees: any[] = []; fetchUsers(count: number) { this._http.get(`https://jsonplaceholder.typicode.com/users`).subscribe( ...

Declaration of Typescript index.d.ts for a heavily nested function within an npm module

Regrettably, it appears that @types/rickshaw is lacking content, prompting me to create my own declaration file. The current one I have looks like this: declare module 'rickshaw' { export class Graph { constructor(obj: any); ...

Guide on setting up a chart using data fetched from an API?

I'm looking to incorporate ngx-charts into my project, but I'm struggling with initializing the chart with data retrieved from my API. Setting up a vertical bar chart seems straightforward. The data structure I have is like this: https://stackb ...

React - Component not updating after Axios call in separate file

Recently I decided to delve into React while working on some R&D projects. One of my goals was to build an application from scratch as a way to learn and practice with the framework. As I started working on my project, I encountered a rather perplexin ...

Encountering an Issue: Unable to connect with 'ngModel' as it is not recognized as a valid property for 'input' even after importing FormsModule

Despite importing FormsModule in my app.module.ts, I am still encountering the following error message. 'Cannot bind to 'ngModel' since it isn't a known property of 'input' I have thoroughly reviewed similar posts, but unf ...

Tips for transferring several parameters from an Angular 8 application to a .NET Core API

Hello, I am facing an issue with passing multiple string parameters from an Angular 8 app to a .NET Core API. This is my first time posting a question so I will try to provide all the necessary details. Here is the Angular code snippet: import { Injectab ...