The error occurred when trying to assign a value to a property 'id' that is not defined

Currently in my Angular 7 project, I am working on posting a request to the server. The data is being collected from an Angular reactive form and needs to follow a specific structure.

{
    "title" : "Test Title",
    "user": {
        "id" : 7
    },
    "category": {
        "id" : 2
    },
    "description" : "test description",
    "quantity" : 2
    
}

Additionally, here is the model class that corresponds to this structure.

export class SampleRequest {
  title: string;
  category: { id: number};
  user: { id: number};
  description: string;
  quantity: number;
}

In order to populate the SampleRequest object correctly, it's best to assign each element individually due to limitations with directly adding user Id and category Id. If there are any mistakes in this approach, please let me know.

Moreover, here is the sample-request.ts class I have implemented for handling this process.

  requestForm: FormGroup;
  sampleRequest: SampleRequest = new SampleRequest();
  isSuccessful = false;
  isFailed = false;
  isProgress = false;
  errMsg: string;

  constructor(private fb: FormBuilder, private userService: UserService, private tokenStorage: TokenStorageService) { }

  ngOnInit() {
    this.requestForm = this.fb.group({
      title : ['', Validators.required],
      category : ['',Validators.required],
      description: ['', Validators.required],
      quantity: ['', [Validators.required, Validators.pattern]]
    });

  }



  onSubmit() {
    this.sampleRequest.title = this.requestForm.get('title').value;
    this.sampleRequest.category.id = this.requestForm.get('category').value; //encountering an issue here
    this.sampleRequest.user.id = this.tokenStorage.getUser().id;  //as well as here
    this.sampleRequest.description = this.requestForm.get('description').value;
    this.sampleRequest.quantity = this.requestForm.get('quantity').value;
    console.log(this.sampleRequest);
    this.userService.newSampleRequest(this.sampleRequest)
      .subscribe(
        data => {
          this.isSuccessful = true;
          this.isProgress = true;
        },
        error => {
          this.isFailed = true;
          this.isProgress = true;
          this.errMsg = error.error.message;
        }
      );
  }

}

Unfortunately, when testing this implementation, I encountered the error "TypeError: Cannot set property 'id' of undefined." The user Id is meant to be assigned based on the logged-in user's ID retrieved from JWT token, while the category Id should come from the reactive form.

Answer №1

Even with the current code structure, the user and category components within the SampleRequest object will remain undefined.

const sampleRequest = new SampleRequest();

To resolve this issue, you can create new empty objects for both category and user, and then assign them to the sampleRequest object:

sampleRequest.category = {};
sampleRequest.user = {};

By doing this, the error message "TypeError: Cannot set property 'id' of undefined" should no longer occur.

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

How can I effectively retrieve a value from Ionic storage and use it as an authorization token instead of receiving the promise "Bearer [object Promise]"?

In my Ionic 4 angular project, the storage.get('token').then() function returns a promise object instead of the refresh token. For JWT authentication, I send the access token as the bearer token in the authorization headers using an HTTP interce ...

Automatically Formatting Currency in Angular 6 with Keyup

I am currently facing an issue with using the keyup event in an input element that has a currency pipe in my Angular 8 application. <input placeholder="€0.00" (keyup)="onKey(pointIndex, $event.target.value, item.quantity)" value="{{item.unitPriceWith ...

What is the best way to access data from a local JSON file in Gatsby when using TypeScript and GraphQL?

I'm updating my former gatsby site using TypeScript. I encountered an issue while trying to retrieve data from a local JSON file: There appears to be an error in your GraphQL query: Cannot find field "allNavigationLinksJson" on type "Q ...

Sending an array using json through Ajax

I am working with dynamically generated textboxes through Ajax. To parse JSON, I am using the Jackson 1.9.8 library. Using jQuery, I can retrieve the values of these dynamic textboxes in the following manner: var itemsArray=[]; $('input[name="txtCha ...

Unable to modify the value of a key within an object using TypeScript

I'm struggling to update the value of a key within an object using TypeScript. Here's an overview of the types I'm working with: export enum BAR_TYPES { apple = "apple", banana = "banana" } export type BarTypes = ...

Can you specify the nature of the clear dispatch action?

Below is the code snippet in question: useEffect(() => { dispatch(fetchMovieDetails(movieId!)); return () => dispatch(fetchMovieDetails(movieId!, "clear")); }, [dispatch, movieId]); The issue at hand is that this code snippet i ...

Is it possible to execute "green arrow" unit tests directly with Mocha in IntelliJ IDEA, even when Karma and Mocha are both installed?

My unit tests are set up using Karma and Mocha. The reason I use Karma is because some of the functionality being tested requires a web browser, even if it's just a fake headless one. However, most of my code can be run in either a browser or Node.js. ...

Sharing information between components in Angular through service communication

In my Angular 4 project, there is a functionality where upon clicking on one of the 'groups', its tile should be added to a list of 'favourites' which is represented as an array. To implement this feature, I utilized a BehaviorSubject. ...

Tips for updating a JSON file in PowerShell by replacing a specific string with a variable

I have a JSON object shown below. I am looking to substitute the '$content' value with 'test/abc' in the JSON. { "$version": "0.0.1", "description": "", "content": { "url": "$content", "tag": { "version": "0.0.1", ...

Using FormControl Inheritance in Angular 4

My goal is to enhance the functionality of a FormControl by creating a subclass with additional properties. These properties will then be utilized in custom form controls to modify behavior. I attempted to inherit from FormControl (let's call it Stan ...

Constantly loading image with Meteor HTTP request

Within my Meteor application, I am attempting to dynamically load a random image from an API which returns JSON data structured like this: { "id":2026 "url": "https:// ... " , "large_url":null, "source_id":609, "copyright":"CC0", "site":"unsplash" } ...

Unlocking the Power of Passing Props to {children} in React Components

Looking to create a reusable input element in React. React version: "react": "17.0.2" Need to pass htmlFor in the label and use it in the children's id property. Attempting to pass props to {children} in react. Previously attempte ...

Flipping json stringify safety

In my NextJS React application, I encountered an issue with circular references when using getInitialProps to fetch data. Due to the serialization method used by NextJS involving JSON.stringify, it resulted in throwing an error related to circular structur ...

Having trouble with my Angular application, seems to be stuck at the loading screen. Not sure what's causing it, possibly

Hey there, I'm hoping to create a straightforward app that showcases posts. However, I've encountered an issue when deploying the initial page which is stuck on "Loading...". I believe it's a minor problem and would appreciate your assistan ...

Transmit data in JSON format from PHP script to AJAX

I've developed a PHP class that fetches data from a database and returns the results in JSON format: public function getCategories() { if (!$this->isConnectionAlive()) { $this->getConnection(); } $data = $this->dbconn-&g ...

Encountering issues during postinstall when trying to npm install the classlist.js package using

I am facing an issue on Windows 10 with the latest update. My npm version is 5.4.1 and despite trying multiple solutions from various sources like StackOverflow and GitHub, I am unable to resolve it. Some of the things I have tried are: Using command pro ...

The useEffect hook in React is signaling a missing dependency issue

Any tips on how to resolve warnings such as this one src\components\pages\badge\BadgeScreen.tsx Line 87:6: React Hook useEffect has a missing dependency: 'loadData'. Either include it or remove the dependency array react-hoo ...

The addition operator cannot be used with the Number type and the value of 1

Encountering an issue where the operator '+' cannot be applied to types 'Number' and '1' buildQuerySpec() { return { PageSize: this.paging.PageCount, CurrentPage: this.paging.PageIndex + 1, MaxSize: '' ...

How to retrieve a specific property from an array within an object using Typescript

I'm currently working on accessing information from a blog using Typescript. I'm having trouble figuring out how to access the title item since it is within an array. export default function Post({list}: Props) { console.log(" ...

Retrieving the image field value using FSS in Plone 3.x

I am currently in the process of transferring an older Plone 3.3 website that utilizes FileSystemStorage with the help of Mikko's Simple JSON export script. Everything seems to be working smoothly, with the exception of missing values in the image fi ...