While working in my typescript file, I encountered an issue with the line "this.productForm.patchValue(result.data)". The error states that the object 'Result' may be null. My goal is to populate the form data when the Edit option is clicked. Here is a snippet of my code-
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators} from '@angular/forms';
import { ProductService } from '../services/product.service';
import { Product } from '../models/product';
import { ActivatedRoute, Router } from '@angular/router';
@Component({
selector: 'app-create-product',
templateUrl: './create-product.component.html',
styleUrls: ['./create-product.component.css']
})
export class CreateProductComponent implements OnInit {
productForm:FormGroup;
title: any;
id: any;
constructor(
private fb: FormBuilder,
private productService: ProductService,
private route: ActivatedRoute,
private router: Router
) {
this.productForm = new FormGroup({
name: new FormControl(null),
email: new FormControl(null),
number: new FormControl(null),
address: new FormControl(null)
});
}
ngOnInit(){
this.title = "Create Product";
this.createForm();
this.id = +this.route.snapshot.params.id;
console.log(this.route.snapshot.params.id)
if(this.id){
this.getProduct();
}
}
createForm(){
this.productForm = this.fb.group({
name:[''],
email:[''],
number:[''],
address:['']
})
}
onSubmit(){
console.log(this.productForm.value);
if(this.id){
this.updateProduct();
}else{
this.addProduct();
}
}
updateProduct(){
this.productForm.value.id = this.id;
this.productService.updateProduct(this.productForm.value).subscribe(
result =>{
console.log(result);
this.router.navigateByUrl('/backend/product');
}
)
}
getProduct(){
this.productService.getProduct(this.id).subscribe((result) => {
console.log(result)
this.productForm = new FormGroup({
name: new FormControl( result ['name']),
email: new FormControl( result ['email']),
number: new FormControl( result ['number']),
address: new FormControl( result ['address'])
})
}
)
}
}
I have attempted several methods to resolve this issue without success. Can you provide suggestions for improvement?