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.