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;
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