Error encountered while making an Angular POST request with object parameter

Need to make a post request to update the current user on the home page. The expected url for the post should be in this format: "http:......./user/id". However, when the request is sent, the url becomes "http:/...../user/[object%20Object]" which causes an error. What steps can be taken to resolve this issue?

Service;

updateUser(id: number): Observable<User> {
  return this.http.put<User>(`${this.url}/${id}`, id)
}

User.ts;

export interface User {
  id: number
  firstName: string
  lastName: string
  username: string
  mail: string
  password: string
}

home.component;

updateUser(id: number) {
  this.router.navigate(['update', id]);
}

update.component;

export class UpdateUserComponent implements OnInit {

  user?: User
  data: any

constructor(private service: AppService, private route: 
ActivatedRoute, private router: Router) { }

  ngOnInit(): void {
  }

  form = new FormGroup({
    firstName: new FormControl('', [Validators.required]),
    lastName: new FormControl('', [Validators.required]),
    username: new FormControl('', [Validators.required]),
    mail: new FormControl('', [Validators.required]),
    password: new FormControl('', [Validators.required]),
  })

  submit() {
    this.data = this.form.value
    console.log(this.data)

    this.service.updateUser(this.data).subscribe(data => {
      console.log(data)
    })

    this.router.navigate(['/']);
  }

}

Answer №1

When utilizing the updateUser method in your service, make sure to pass two parameters: the id and the data object of the form values. This will prevent the display of [Object%20Object].

Update your service code to reflect this:

updateUser(id: number, data: User): Observable<User> { 
 return this.http.put<User>(`${this.url}/${id}`, data)
}

In the update.component.ts file, adjust the submit method to extract the id from the route parameter and pass it into the updateUser service method.

submit() { 
  this.data = this.form.value;
  const id = this.route.snapshot.params['id'];
  this.service.updateUser(id, this.data).subscribe(data => {
    console.log(data)
  })

These changes should resolve the issue at hand.

Answer №2

Instead of sending the entire form to the service, you should only send the id that is expected. Make sure to update the service and send both the id and the form value!

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

Gulp failing to produce inline sourcemaps

I have a specific tsconfig.json setup within an ASP.NET Core project: { "compilerOptions": { "target": "es5", "module": "commonjs", "moduleResolution": "node", "inlineSourceMap": true, "inlineSources": true, "emitDecoratorMetadat ...

Using Selenium to test an iframe located within a shadow DOM

I have an Angular application with ViewEncapsulation.ShadowDom enabled, and within this app, there is an iframe. However, when attempting to write a Protractor test, I am encountering the following error: Failed: unknown error: no element reference returne ...

Simple guide on utilizing @ViewChild in Angular 2 to access dynamically added HTML tags for dynamic loading

I am working on a component that utilizes an external JavaScript file (datatables). As I render the table using datatable(), I am structuring the view of the table. This includes the following: <td class=" details-control"></td> While identif ...

Struggling with hashtags and ampersands in Angular when making an HTTP request

Dealing with Special Characters # and & in Angular's http.get() Request URL Take a look at my code first. Angular Service let versionsearch = "&"; let strweeksearch = "%23"; this.http.get(this.apiUrl + 'GetVersionInfo?vehicleVersion=' + v ...

Arrange photos in a grid using React Dropzone uploaders

I'm having trouble figuring out how to create a custom preview similar to an image set in a grid using the react-dropzone-uploader component for uploading multiple files. Currently, when I upload images, they are displayed as shown in my normal uploa ...

Using Typescript to return a specific data type

I am facing an issue with my dataSync service where TypeScript is referring to the returned data as type object instead of type <WebPost>, which is causing my code to break. In the dataSync service, I receive an error when hovering over the data para ...

Adding a constant to a Vue component

Currently working on developing an application using Vue and TypeScript. I'm focused on refactoring some aspects, particularly moving hard-coded strings from a template to a separate constant. What has been implemented is as follows: export const va ...

Top method for verifying input during keyup or blur events

When it comes to validating user inputs, I often find myself wondering about the best approach to take. In this case, I have created a regex for numbers with decimal points. .ts part checkIsNumber(event) { console.log('event', event.target. ...

Troubleshooting Laravel 5 CRUD Operations: Common Errors and Solutions

Recently, I started using Laravel and decided to implement CRUD functionality. However, I encountered two errors along the way, with one of them being as follows: ErrorException in UrlGenerator.php line 304: Route [Item.store] not defined. (View: C:\ ...

The value of NUMBER_VALUE cannot be transformed into a String while trying to update the Item

I've encountered a strange issue with DynamoDB where I'm unable to update an item. Below is the command I'm using: TableName: 'UserTable', Key: { UID: { S: 'h4XJj3YRxZiF7TDcGkxAhc' } }, UpdateExpression: 'SET numRat ...

Unable to send back calculation result to the server

After clicking the submit button, I encountered a problem where a 404 error was displayed, stating "Cannot POST /Index" on the website. Unsure if this is caused by logical issues within the code or syntax-related problems. The program does not involve any ...

Creating an object key using a passed literal argument in TypeScript

Can the following scenario be achieved? Given an argument, how can we identify the object key and access it? Any potential solutions? async function checkKey(arg:'key1'|'key2'){ // fetchResult returns an object with either {key1:&apo ...

Having issues with my custom NextJS server implementation using TypeScript

I am currently exploring the use of a custom server with NextJS in conjunction with TypeScript. In order to do this, I must utilize the nextjs createServer function. Everything is functioning correctly when using the require syntax: const next=require(&ap ...

How to refresh an Observable in Angular 2

Description: Presently, I am utilizing Angular2 (now updated to Angular4). In my component's constructor, I am subscribing to a service using the code: this.policyService.getBaseCommission().subscribe(response => response). The data obtained from ...

VSC is throwing a type error, but is it still possible to compile the code?

It seems like after downloading some extensions, I started encountering this issue which was not present before. My files are now displaying errors even though everything should be fine. https://i.sstatic.net/cr7Ef.png The error seems to be related to ca ...

How to access NavController in an Ionic2 service provider

In my Ionic2 app, I have created an AuthHttpProvider which acts as a wrapper for Http requests and automatically adds an authentication token (jwt) to each request. I use this instead of the default Http provider in all of my interactions with the server. ...

Leveraging the information retrieved from Promise.all calls

Using the service method below, I send two parallel queries to the server with Promise.all. The returned results are stored in the productCategoryData array, which is then logged to the console for verification. Service method public getProductCategoryDa ...

Tally of specified time frame

I have a collection of dates presented as follows: [ "2020-08-20", "2020-08-20", "2020-08-21", "2020-08-24", "2020-08-25", "2020-08-25", "2020-08-25", ] and I am in need of segregating ...

Found within the ProductsModule NgModule.imports, a reference that could not be resolved to a valid NgModule class was discovered

I am currently working on a multi-module Angular project and have developed my own ImagegalleryComponent to be used across multiple modules. However, every time I try to import it in different modules, I encounter various issues. Even when I import it in t ...

What is the best way to delay an Angular HTTP Post until receiving a response from node.js?

Hey there, I am currently new to Angular/Node JS and working on a project for my university. I am trying to implement authorization/authentication in both the frontend and backend. I have created a method called Login in Node JS and tested it using Postma ...