Unable to access the values of the object within the form

I am encountering an issue where I cannot retrieve object values in the form for editing/updating. The specific error message is as follows:

ERROR TypeError: Cannot read properties of undefined (reading 'productName')
    at UpdateProductComponent.ngOnInit (update-product.component.ts:63:33)
    at callHook (core.mjs:2576:22)
    at callHooks (core.mjs:2545:17)
    at executeInitAndCheckHooks (core.mjs:2496:9)
    at refreshView (core.mjs:11622:21)
    at refreshEmbeddedViews (core.mjs:12812:17)
    at refreshView (core.mjs:11631:9)
    at refreshComponent (core.mjs:12858:13)
    at refreshChildComponents (core.mjs:11348:9)
    at refreshView (core.mjs:11657:13)

Within my productservice.ts file, I have the following method defined:

  getProductById(id: number){
    return this.http.get<Product>(`${this.baseUrl}/getProductById/${id}`);
  }

This function successfully retrieves the id or productId without any issues,

In my main component, I can redirect to a new page/UpdateProductComponent using the following code:

updateproduct = (productId: any) => {
  this.router.navigateByUrl('/updateproduct',  productId)
};

Within my UpdateProductComponent, the implementation looks like this:

  product: IProduct;
  id: any;

  ngOnInit() {

    this.id = this.route.snapshot.paramMap.get('id');
this.productService.getProductById(this.id).subscribe((data: Product)=>{
            this.product = data;
      console.log(this.product),              // successfully retrieves the data
      this.updateForm.patchValue({
        // productId: this.id,                // works 
        //   productName: 'asdas',            // works 
        productId: this.product.productId,    // does not work
        productName: this.product.productName // does not work
      })
    });
  }

I can confirm that the data is fetched correctly under network tab > payload for that product in the format: [{"productId":"2","productName":"23123","productDescription":"wqeq","productCategory":"qewqweq","units":23}]

*** Update *** After updating my service to return an Observable, the error is resolved but the values are still not populating in the form.

Answer №1

Consider implementing this modification within your platform

retrieveProductWithId(identifier: number): Observable<Product> {
   return this.http.get<Product>(`${this.baseUrl}/getProductById/${identifier}`);
}

Answer №2

The JSON response attached is an array of Product objects.

[{"productId":"2","productName":"23123","productDescription":"wqeq","productCategory":"qewqweq","units":23}]

The service expects to receive and return a single Product item.

To achieve this, update the getProductById method in the ProductService to use rxjs' .map() function to extract the first item from the array.

import { map, Observable } from 'rxjs';

getProductById(id: number): Observable<Product> {
  return this.http.get<Product[]>(`${this.baseUrl}/getProductById/${id}`)
    .pipe(map((response: Product[]) => response[0]));
}

Check out the StackBlitz Demo for reference

This modification will enable you to bind the API response value to form controls as mentioned in the previous question.


Note:

this.updateForm.patchValue({
  productId: this.product.productId,
  productName: this.product.productName,
});

should be replaced with:

this.updateForm.patchValue(this.product);

as explained in the previous question.

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

Struggling to make fetch function properly within a NextJs middleware function

I am having trouble with redirecting a user to /login if the authentication token from Laravel is invalid. I am attempting to retrieve the user and, if resp.ok() returns false, delete the invalid "token" cookie and direct the user to /login. However, I con ...

Delete a particular item from a JSON object in real-time using TypeScript/JavaScript

Upon examining the JSON data provided, it contains a node called careerLevels which includes inner child elements. input = { "careerLevelGroups": [ { "201801": 58, "201802": 74, ...

Encountering errors while running Angular 8's ng build prod command

After successfully migrating my project from Angular 7 to Angular 8, I encountered an issue when attempting to run 'ng build prod' which resulted in the following error: ERROR in Error during template compile of 'Ng2CompleterModule' Cou ...

The guide to integrating the npm package 'mysql-import' into a node.js project with TypeScript

I'm currently facing an issue while trying to import a dump to a database using node.js and the npm module 'mysql-import'. Initially, I wrote the code in JavaScript and it worked flawlessly. However, when I attempted to modify it for TypeScr ...

Clearing text fields in jQuery by cloning them

I am attempting to duplicate the friend fields (name + email) when the "add another friend" button is clicked. However, the cloned fields end up including the text inside them, which is not desired! Does anyone have any suggestions or solutions? Here is t ...

What's the deal with the Zod getter function?

Is it possible to create a getter function within a Zod object? For instance, in ES5 you can achieve the following: const person = { firstName: "John", lastName: "Doe", get fullName() {return `${this.firstName} ${this.lastName}`} } person.fullNam ...

Typescript compilation fails to include require statements in certain files

Currently, I am in the process of converting a Node.js project to TypeScript. The first two main files of the Node project transpiled correctly, but the third file ran into issues with the requires statement at the top for pulling in dependencies. Despite ...

Verification forms and age detection algorithms

Recently, I designed a website dedicated to a particular beer brand which required an age verification page. The PHP script that handles the verification utilizes sessions to store the verification status. This script redirects all visitors to the verifica ...

Invoking a function on an object of a subclass that derives from an abstract class

In the realm of abstract classes, behold this one: export abstract class BaseStepComponent { /** Behold thy base-step ctor */ constructor() { } abstract getValue(): string; } And lo, here is a component that inherits such abstract glory ...

How to implement separate environment.ts files for different languages in Angular 12? For example, environment.en.ts and environment.de.ts files

Recently, I've been developing a multi-language Angular application and successfully deployed it to Firebase hosting. If you visit , you'll see the German version. On the other hand, displays the English version of the app. One challenge I enc ...

Utilizing Angular CLI configuration for End-to-End testing purposes

I'm currently in the process of updating an Angular CLI project to version 6 The issue I'm facing is that prior to version 6, I could run the command ng e2e -e=e2e and the tests would execute smoothly with the specified environment. However, in ...

Combine two arrays of data sources

mergeThreads() { const userId = this.auth.getUser().uid; const buyerThreads$ = this.afs.collection('threads', ref => ref.where('buyerId', '==', userId)).valueChanges(); const sellerThreads$ = this.afs.collection ...

The function Sync in the cp method of fs.default is not a valid function

When attempting to install TurboRepo, I encountered an issue after selecting npm. >>> TURBOREPO >>> Welcome to Turborepo! Let's get you set up with a new codebase. ? Where would you like to create your turborepo? ./my-turborepo ...

What is the reason behind starting certain scripts using "npm start x" while others only require "npm x"?

Within the package.json file, I have included a section dedicated to defining scripts for various tasks: "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build --prod", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e" }, ... When lau ...

Preventing recursive updates or endless loops while utilizing React's useMemo function

I'm currently working on updating a react table data with asynchronous data. In my initial attempt, the memo function doesn't seem to be called: export const DataTableComponent = (props: State) => { let internal_data: TableData[] = []; ...

Generating a composer method in TypeScript (Flow $Composer)

While flow supports $Compose functions, the equivalent mechanism seems to be missing in TypeScript. The closest thing I could find in TypeScript is something like https://github.com/reactjs/redux/blob/master/index.d.ts#L416-L460. Is there a native equivale ...

What role does enum play in typescript?

What is the purpose of an enum in typescript? If it's only meant to improve code readability, could we achieve the same result using constants? enum Color { Red = 1, Green = 2, Blue = 4 }; let obj1: Color = Color.Red; obj1 = 100; // IDE does not sh ...

Customize back button functionality in Ionic 2

Is it possible to modify the behavior of the back button shown in this image? I would like to specify a custom destination or perform an action before navigating back, instead of simply returning to the previous page. https://i.stack.imgur.com/EI2Xi.png ...

Include the complete path to the base href within an Angular application

How can I retrieve the base href in Angular, including the domain (or subdomain)? Here is a use case: I need to add the og:image property using the Meta service. The current content shows as /image.jpg, but I want it to display as https://example.com/ima ...

Dynamic row insertion in Angular Material table during sorting操作

I utilized Angular material to create a table which looks like this: <mat-table #table [dataSource]="dataSource" matSort> <ng-container *ngFor="let item of displayedColumns; let i = index" cdkColumnDef="{{getColumnName(i)|Formater:'clean&apo ...