The issue encountered is: "Unable to assign property 'id' to a numeric value of '1' in Angular."

In my Angular 7 project, I am trying to establish a client-side request to the server-side. Below is the structure of the request that needs to be sent.

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

Describing the model class in Angular:

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

The input data is gathered through Angular Reactive forms. The user Id originates from the JWT token, representing the currently logged-in user. Here is a snippet from the template file 'sample-request.component.html':

<form novalidate [formGroup]="requestForm" (ngSubmit)="onSubmit()">
        <p>
          <mat-form-field class="form-field-width">
            <input matInput placeholder="Title" type="text" formControlName="title" name="title" required>
            <mat-error *ngIf="requestForm.get('title').hasError('required')">Title is required</mat-error>
          </mat-form-field>
        </p>

... Content truncated for brevity ...

      </form>

Now moving on to 'sample-request.component.ts' file:

export class SampleRequestComponent implements OnInit {

  requestForm: FormGroup;
  sampleRequest: SampleRequest;


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

  ngOnInit() {
    this.requestForm = this.fb.group({
      title : ['', Validators.required],
      category : [''],
      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;
    this.sampleRequest.user.id = this.tokenStorage.getUser().id;
    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;
        }
      );

  }

}

I encountered an issue where 'title' came up as undefined during execution.

Answer №1

the ExportSampleRequest you are working with is currently undefined

export class ExportSampleRequest {
  name: string;
  user: { id: number};
  category: { id: number};
  description: string;
  quantity: number;
}

you must initialize it as a class like this

exportSampleRequest: ExportSampleRequest = new ExportSampleRequest();

this will allow you to access all properties of your export sample request in this.exportSampleRequest

Answer №2

Upon reviewing your code, I noticed a couple of things.

  1. You have implemented reactive forms, in which case using formControlName alone is sufficient. Angular can identify the field name with just this specification.
  2. If you are using a number type in an input field and fetching its value using .value, it will return a string. Therefore, attempting to assign a string to a number in TypeScript may result in an error or warning.

Addressing these issues might help you better comprehend and resolve the problem. Thank you.

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

Issue deploying serverless: Module '/Users/.../--max-old-space-size=2048' not found

Everything is running smoothly on my serverless project locally when I use sls offline start. However, when I attempt to deploy it through the command line with serverless deploy, I encounter the following error stack. internal/modules/cjs/loader.js:1030 ...

The table on the page shifts position when viewed on different devices, sometimes not remaining between the header and footer

Here is a link to see how my page looks with the header, table, and footer: If you want to see how it looks when responsive (with smaller width), check out this link: I have encountered 2 main problems: The table overlaps the header, The footer ends up ...

Exploring [routerLink] vs routerLink: Unraveling the Distinctions

Can you explain the distinction between [routerLink] and routerLink in Angular routing? What are the advantages of each one and which should be used? Understand the difference ...

The installation failed due to an unresolved dependency when running npm install

Upon performing a git clone, I encountered this error with my project after running npm install: npm ERR! code ERESOLVE npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6e0f1e1e43081c01001a0b000 ...

Tips for accessing an API and setting up data mapping for a data table in nuxt.js

I desperately need assistance. I have been struggling with this issue for a while now, but all my attempts have ended in failure. My objective is to retrieve API data that corresponds to an array containing name, id, and email, and then display this inform ...

Unique: "Unique styling for Ionic on emulator versus web localhost"

My perception of CSS codes in browsers versus emulators differs. I believe that currently, CSS codes only work properly in browsers. For instance, I attempted to change -ion-background-color for .md body and iosbody. However, the emulator still displays t ...

Attention! Circular dependency has been detected during compilation with warnings

Every time I attempt to build my project, an error is thrown- WARNING in Circular dependency detected: src\app\own-filter\own.filter.module.ts -> src\app\own-filter\own.filter.component.ts -> src\app\own-f ...

Access uninitialized properties in Typescript post-compilation

I am currently in the process of creating a wrapper for socket.io. Coming from a strong object-oriented background, I aim to incorporate the idea of Models into my framework/wrapper. For those familiar with socket.io, you may know that data associated wit ...

The attribute 'selectionStart' is not a valid property for the type 'EventTarget'

I'm currently utilizing the selectionStart and selectionEnd properties to determine the beginning and ending points of a text selection. Check out the code here: https://codesandbox.io/s/busy-gareth-mr04o Nevertheless, I am facing difficulties in id ...

Struggling with declaring generic types in TypeScript can be a challenge

Struggling with declaring the type while creating a hook named useUpdate, here's the code: type CallBack<T extends readonly any[]> = ( ...args: T ) => void | (() => void | undefined); function useUpdate<T extends readonly any[]>( ...

Time taken for a webpage to finish loading

Is there a way to programmatically obtain the page load time in an Angular application? Situation: On my dashboard page, various components are making multiple calls. I want to calculate the overall time it takes to load all widgets on the page. ...

Invoke a function within the embedded element

I currently have two components, known as app-student-list and app-student-detail. My goal is to incorporate the student-detail within the student-list in the following manner: Within app-student-detail.html: <p>Student Detail Component content go ...

Angular allows cross-origin requests with Access-Control-Allow-Origin

Hi, I am facing an issue with the update function in my app. Whenever I try to update, it shows me the following error message: Failed to load http:// localhost:8080/../update: Response to preflight request doesn't pass access control check: No &apo ...

Is the translation pipe in Angular 5 impure?

I'm currently utilizing ngx-translate. Can you tell me if the translation pipe is considered pure or impure? Also, would it be more beneficial to use the directive syntax translate="X" instead? ...

Resolve the issue of text overlapping on an image when zooming in

There seems to be an issue with overlapping text and images when zooming the page. I have included a screenshot for reference, please take a look and provide a solution. Thank you in advance. Here is the CSS code causing the overlap: .Pad{ padding: 6 ...

Unable to access or modify properties within a function passed as an argument

deleteDialog(item, func: Function) { this.dialogService .open(ConfirmDialogComponent, { context: { title:"Are you sure?", cancelClss: "info", confirmClss: "danger", }, ...

Is there a way to stop Material UI from dulling the color of my AppBar when using dark mode in my theme?

When I use mode: "dark" in my Material UI theme, it causes the color of my AppBar to become desaturated. Switching it to mode: "light" resolves this issue. This is how my theme is configured: const theme = createTheme({ palette: { ...

Unable to retrieve local property when inside a Callback function in Ionic2

I am encountering an issue with my Ionic 2 app that utilizes Angular2. It is a basic problem, but it has been quite frustrating for me. Below is the component in question... import {Component} from "@angular/core"; @Component({ '<ion-content> ...

Incorporating fresh components and newly defined attributes in Angular

Is there a way for me to click on a new component button, specify a name, description, select type, and add attributes such as default value and type? I need all this information to be saved and for the new button to appear in the drag-and-drop section. ...

Identifying modifications within the @Input property in Angular 4

Can someone clarify how to detect changes in an @Input property within a component, rather than just when passed from its parent? I haven't found a clear answer to this yet. Thank you! ...