Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

angular post request [object%20Object] error

I want to update the current user on the home page with the following post request. url: "http:…../user" and the url required for the post should be: "http:……./user/id" but the url is sent as http:/…../user/[object%20Object] and I get an error. how should I go about fixing this?

Service;

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

User.ts;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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(['/']);
  }

}

>Solution :

You are passing only one parameter to your udateUser method in the service and that is not id but the whole form value object thats why its showing [Object%20Object].

update the code inside your service and pass id and data two parameters

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

modify submit method inside update.component.ts file to get id from route param and pass to 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)
  })

Hope this works

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading