What is the best method for saving information from a service to a class or interface in Angular 2?

I am currently in the process of developing a new web application and I am fairly inexperienced with Angular2. I am encountering an issue with one of my components that acts as a form for users to update their data.

The problem lies in accessing specific data within my JSON file. I have attempted to store the data in an object of a class but it seems like my implementation might be incorrect, as it is not achieving the desired functionality. Below is my UserDetailsComponent:

UserDetailsComponents.ts

import { Component, OnInit, OnDestroy, ViewChild  } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { FormControl, FormGroup, FormBuilder, Validators } from '@angular/forms';
import { ModalDirective } from 'ng2-bootstrap/modal/modal.component';

import { ApiService } from '../../assets/services/api.service';

import { UserDetails } from '../../assets/classes/user-details';

@Component({
  selector: 'app-user-details',
  templateUrl: './user-details.component.html',
  styleUrls: ['./user-details.component.scss']
})
export class UserDetailsComponent implements OnInit, OnDestroy {

    id: any;
    data: UserDetails;

    private sub: any;

    constructor(
      private route: ActivatedRoute,
      private apiService: ApiService,
      private fb: FormBuilder) {}

    ngOnInit() {
      this.createForm();
      this.sub = this.route.params.subscribe(params =>{
        this.id = params['id']; //console.log(this.id);
        this.apiService.getUserById(this.id).subscribe(values => 
          this.data = values[0];
         ) 
      })
    }
}

And below is my userDetails class

UserDetails.ts

export class UserDetails {
    id: string;
    first_name: string;
    last_name: string;
    status: boolean;
}

My goal is to simply use this.data to access the id, first_name, last_name, and status within the component.

Example

createForm(data){
      this.userDetailForm = this.fb.group({
        id: [this.data.id],
        first_name: [this.data.first_name, Validators.required],
        last_name: [this.data.last_name, Validators.required],
        status: [this.data.status, Validators.required]
      });
}

Any assistance or guidance on resolving this issue would be greatly appreciated. Thank you.

Answer №1

To ensure the form is populated correctly, it is important to create the form after retrieving data or initialize and then set values upon receiving the data. Here's an example of how you can build the form after fetching data:

ngOnInit() {
  this.sub = this.route.params.subscribe(params =>{
    this.id = params['id']; //console.log(this.id);
    this.apiService.getUserById(this.id).subscribe(values => {
      this.data = values[0];
      this.createForm();  // create form after fetching data
    }) 
  })
}

createForm(){
      this.userDetailForm = this.fb.group({
        id: [this.data.id],
        first_name: [this.data.first_name, Validators.required],
        last_name: [this.data.last_name, Validators.required],
        status: [this.data.status, Validators.required]
      });
}

Remember to use *ngIf in your template to prevent rendering the form before it is created, thus avoiding any errors in your app.

<form [formGroup]="userDetailForm" *ngIf="userDetailForm">

Answer №2

update your ngOnInit function

 ngOnInit() {

      this.sub = this.route.params.subscribe(params =>{
        this.userID = params['id']; //console.log(this.id);
        this.userService.fetchUserById(this.userID).subscribe(info => 
          this.userData = info[0];
          this.setupForm(this.userData);
         ) 
      })

modify your setupForm function as follows:

setupForm(userData){
      this.userProfileForm = this.fb.group({
        id: [userData.id],
        first_name: [userData.first_name, Validators.required],
        last_name: [userData.last_name, Validators.required],
        status: [userData.status, Validators.required]
      });
}

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

Angular reference numbers vs ngModel

When is it necessary to use [(ngModel)] on an input, and when can I simply use #reference? For instance: <div class="form-group"> <div class="input-group mb-2"> <input type="text" class="form-control" [(ngModel)]="newUser"> < ...

I am looking to replicate a DOM element using Angular 4

I am interested in creating a clone of a DOM element. For example, if I have the following structure: <div> <p></p> <p></p> <p></p> <p></p> <button (click)="copy()"></button> & ...

ngif directive does not function properly when subscribe is utilized in ngOnInit

this is the unique component code import { Component, OnInit } from '@angular/core'; import { Subscription } from 'rxjs'; //import { Item } from '../item/item.model'; import { CartItem } from './cart-item.model'; imp ...

Implementing query parameters in a Deno controller

I developed a couple of APIs for a Deno Proof of Concept. This is the route implementation: const router = new Router() router.get('/posts', getPosts) .get('/posts/:id', getPostsById) In the second route, I successfully retriev ...

`Warning: The alert function is not working properly in the console error

I am currently working on integrating otp functionality into my Ionic 3 project. I am facing an issue where I am able to receive the otp, but it is not redirecting to the otp receive page due to a specific error. Below is the console error that I am encou ...

Angular 12: TypeScript Issue TS2339 - Unable to Locate Property on Type

Whenever I use the code below, I encounter error TS2339: Property 'timestamp' does not exist on type 'LogRepair[]' In the component's HTML file, I am attempting to loop through an array of properties defined in the LogRepair typ ...

Utilize the ng.IFilterService interface within a TypeScript project

I am facing an issue with a .ts file that contains the following code: module App.Filters { export class SplitRangeFilter implements ng.IFilterService { static $inject = ['$filter']; public static factory(): Function { ...

React-hook-form does not display the input length in a custom React component

Introducing a custom Textarea component designed for reusability, this basic textarea includes a maxlength prop allowing users to set the maximum input length. It also displays the current input length in the format current input length/max length. While ...

Obtain the current state of an Angular Material radio button that has been selected

I am currently working with an Angular Material mat-table that has columns for checkboxes and rows, using Material components for each. Extracting the selected state of the checkbox is straightforward with row.checked, as demonstrated below. However, I am ...

How can we leverage Shared and Core modules alongside Feature modules in Angular development?

When developing my Angular application, I have adopted a specific architecture approach and included a shared.module.ts file in the shared folder. While leveraging lazy-loading in my app, I find myself puzzled about the necessary imports, declarations, and ...

Having trouble personalizing the background color according to the ItemName in angular2-multiselect-dropdown

Is it possible to customize the background color in angular2-multiselect-dropdown based on the tags label? I want the background color to be determined by the tags label. The npm package provides no description regarding this feature here https://i.ssta ...

Creating UI Bootstrap dropdowns using ng-repeat on the fly

As a newcomer to AngularJS and UI Bootstrap, I am facing an issue with adding dropdowns dynamically using ng-repeat. The main problem lies in the fact that when one dropdown is clicked, it triggers all of them simultaneously. It seems like there is some mi ...

The optimal timing for updating the database with new information following a successful Stripe payment is

I'm running into a problem with inserting new order data into my database following a successful payment with Stripe. Here's my Angular code: HTML: <button mat-raised-button color="primary" (click)="checkout()">Ch ...

Learn how to effectively switch tabs and pass data within an Angular Bootstrap application by utilizing the

Recently diving into Angular, I've come across what seems to be a simple problem: transferring data between tabs in an angular bootstrap project. Currently, my main component contains a tab structure (I'll simplify for clarity): <div> ...

Getting the item that was clicked on a Chart in a PrimeNG chart within an Angular application can be achieved by following these

I am trying to implement a bubble chart and I would like the function to be called when a user clicks on one of the bubbles. What is the best way for me to pass the data to this function? https://i.stack.imgur.com/FYiSP.png <p-chart type="bubble" [da ...

Updating a boolean value and passing a body to an Angular HttpClient PUT request

Need help with passing a model in an API Put Request. Also, seeking guidance on including a boolean value concurrently. ...

I'm on the lookout for Angular 2 RC3 bundles – where can I locate them

Due to unforeseen circumstances, I am currently unable to create my own Angular 2 RC3 bundle. Can someone please direct me to where I can find a pre-compiled bundle to experiment with? It seems like the creation of these bundles has stopped once the RC r ...

Angular BreakPointObserver is a powerful tool that allows developers

Hey there! I've been working with the BreakpointObserver and have run into an issue while trying to define breakpoints for mobile and tablet devices. It seems that my code is functioning properly for tablets, but not for mobile devices. Upon further i ...

Dealing with errors when working with an array of Observables in forkJoin: Tips and techniques

In my Angular app, I am fetching an observable stream from an API and I would like to handle errors using forkJoin. import { Observable } from 'rxjs'; import { forkJoin, of, throwError } from 'rxjs'; //Creating an array of observables ...

Tips for preventing repetition of code in multiple entry points in Rollup

My goal is to use rollup to process a group of input files and generate multiple output files in the dist directory that all have some common code shared between them. Below is my current rollup configuration: import path from 'path'; import pat ...