Extract the values from HTTP GET request by Id (Observable) and assign them to variables within the component

Hello everyone, it's been a while since I posted on here. Thank you all for your help so far, but I'm facing some difficulties with my Angular+2 web app. I have a User component and a user.service.ts that handles HTTP requests to get user data in JSON format. However, when I try to set variables in my component using the service, they end up being null or empty. Can anyone provide guidance on how to correctly handle this situation?

I suspect the issue lies within the .subscribe method and Observable concept.

//User service
getUser(id: string): Observable<User> {
        return this.http.get<User>(this.userUrl + "/" + id);   
    } 
//Component

ngOnInit() {
    this.route.params
    .subscribe((params: Params) => {
      this.id = params['id'];
      this.editMode = params['id'] != null;
      this.initForm();
    });
  }
initForm(){
    let id = '';
    let company ='';
    let userNo = 0;
    let email = '';
    let firstName = '';
    let lastName = '';

    // Variables continued...

    if(this.editMode){
      this.userService.getUser(this.id).filter(x => x.id === this.id).subscribe((data: User) => { 

          // Setting user data variables

      });

    }

    // Form initialization

    this.userForm = new FormGroup({
      'company': new FormControl(company, Validators.required),
      'userNo': new FormControl(userNo, Validators.required),
      'email': new FormControl(email, Validators.required),

      // Other form controls...

    })

  }

Answer №1

To ensure proper functionality, it is important to move the

this.userForm = new FormGroup({})
logic inside the .subscribe() block. This will guarantee that the this.userForm is only initialized once the subscription has completed successfully.

In addition, it seems like the subscription is returning a new User object but not storing it anywhere in your code.

A recommended approach would be to create a private method that accepts a User instance as a parameter. This method can handle the creation or updating of the form when not in edit mode, and also cater for editing mode by retrieving user data from the subscription.

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

Tips for incorporating a mail button to share html content within an Angular framework

We are in the process of developing a unique Angular application and have integrated the share-buttons component for users to easily share their referral codes. However, we have encountered an issue with the email button not being able to send HTML content ...

Exploring the functionality of the scan operator within switchMap/mergeMap in RxJS

We're utilizing the scan operator to handle our 'load more' button within our table. This operator allows us to accumulate new results with the previous ones, but we've come across some unexpected behavior. Let's break it down by l ...

Can SystemJS, JetBrains IntelliJ, and modules be combined effectively?

Looking for some clarification on the functionality of module includes and systemJS within an Angular2 app structure. I have set up a basic Angular2 app with the following layout: -app |-lib (contains shims and node libraries) |-components |-app |-app. ...

Searching for the position of different size values according to their specific value

information = { boxNoTo: 1, boxNoFrom: 1, size: 'M', } items = [{ size: 'M', },{ size: 'M', },{ size: 'S,M,L,XS', boxNoTo: 1, boxNoFrom: 1, country: 'CA', name: 'Josh' }] This is what I have don ...

What is the best way to extract accurate information from an observable?

I'm having trouble retrieving the correct data from an observable in my project. Here is the code for my API call: getLastxScans(amount: number): Observable<Scan[]> { return this.http.get<Scan[]>(`${this.ROOT_URL}/Scan/amount/${amo ...

Injecting Dependencies with Angular 2 and the Ability to Include Optional Parameters

One issue I'm facing is that I have multiple components in my Angular 2 application that require the same dependency. This specific dependency needs a string for the constructor. How can I instruct angular2 to use a specific instance of this type for ...

Developing a Typescript "Map" type using numerical enumerations

In my Typescript project, I came across the need to create record types with numeric enums: enum AxisLabel { X = 0, Y = 1 } export const labelLookup: Record<AxisLabel, string> = { [AxisLabel.X]: "X axis", [AxisLabel.Y]: "Y Axis" }; However, I w ...

What is the reason for a class's attributes being considered undefined even after they have been previously set?

Within my code, there is a class called WorkspaceDatabase that stems from the Dynamic Tree Example. I have incorporated some debugging information to gain a clearer understanding of the issue at hand. The Issue: Upon entering the complete() function, an ...

Creating custom functionality by redefining methods in Typescript

My current scenario is as follows: abstract class A implements OnInit{ ngOnInit() { this.method(); } private method() { // carrying out tasks } } class B extends class A implements OnInit { ngOnInit() { thi ...

Initialization of an empty array in Typescript

My promises array is structured as follows: export type PromisesArray = [ Promise<IApplicant> | null, Promise<ICampaign | ICampaignLight> | null, Promise<IApplication[]> | null, Promise<IComment[]> | null, Promise<{ st ...

Struggling to properly import the debounce function in ReactJS when using TypeScript

I am facing an issue while trying to properly import the debounce library into my react + typescript project. Here are the steps I have taken: npm install debounce --save typings install dt~debounce --save --global In my file, I import debounce as: impo ...

I am struggling to make the map method display the specific components I need

Attempting to create a scalable Custom Form using an array of objects and a custom Input field in a React-Typescript project import React, { ChangeEvent } from "react" import { InputField } from "./InputField" interface FormItem { ...

Utilize Typescript to seamlessly transfer data between middleware stages

This is my first time creating an Express app using Typescript. I attempted to transfer data between middleware as I usually do in a JavaScript Express app In my JavaScript application, passing data was seamless What am I doing incorrectly here? Where h ...

Exploring the capabilities of argon2-browser in a cutting-edge setup with vite

After spending several hours attempting to implement the argon2-browser library in a Vue app with Vite, I have been encountering a persistent error. Despite following the documentation closely, I keep receiving the following message: This require call is ...

Are there type declarations in TypeScript for the InputEvent?

Wondering if there is a @types/* module that offers type definitions for the InputEvent object? For more information about InputEvent, you can visit this link. ...

Incorporate service providers into models with Ionic3/Angular4

I am seeking feedback from individuals with more experience than me to determine if my approach is correct. I am currently working on an Ionic3-Angular app that involves a CRUD functionality for "Clientes". From what I have researched, the recommended st ...

What is the most efficient way to remove all typed characters from fields when clicking on a different radio button? The majority of my fields share the same ngModel on a separate page

Is there a way to automatically clear all typed characters in form fields when switching between radio buttons with the same ngModel on different pages? I noticed that the characters I type in one field are retained when I switch to another radio button. ...

Change the value of the checked property to modify the checked status

This is a miniCalculator project. In this mini calculator, I am trying to calculate the operation when the "calculate" button is pressed. However, in order for the calculations to run correctly in the operations.component.ts file, I need to toggle the val ...

Troubleshooting the creation of migration paths in NestJS with TypeORM

After diligently studying the NestJS and TypeORM documentation, I have reached a point where I need to start generating migrations. While the migration itself is creating the correct queries, it is not being generated in the desired location. Currently, m ...

What Causes a Mongoose Query to Result in an Empty Array?

Hello, I have reviewed similar questions regarding the issue I am facing with developing an API. Despite trying different solutions, none seem to resolve my problem. When handling request and response payloads in my API, everything seems to be working fin ...