I have an objects in java backend that i want to change status property on:
@Entity
public class Employee {
@Id @GeneratedValue long id;
private String name;
private String status;
}
I want to set the property status to "Checked" for a targeted object chosen with id with this putmapping:
@PutMapping("/api/users/id")
public Employee changeStatus(@RequestParam Long id)
{
Employee newEmployee = userRepository.getById(id);
newEmployee.setStatus("Checked");
return userRepository.save(newEmployee);
}
I want to do it from my frontend through :
public changeStatus(id: number): Observable<any>
{
return this.http.put<any>(${this.apiServerUrl}/users/id, id)
}
Nothing happens in backend, no errors or anything shows up. What am i missing? I suspect i do something wrong in the frontend call, but i cant figure it out.
Backend-frontend connections seems to work because i can get all data from my backend and see it in frontend with theese two endpoints
Backend:
@RequestMapping("/api/users") public List<Employee> getUsers()
{
return (List<Employee>) userRepository.findAll();
}
Frontend:
public getUsers(): Observable<any>
{
return this.http.get<any>(${this.apiServerUrl}/users)
}
Thanks in advance!
CodePudding user response:
Are you subscribing to this call on the FE ? the angular HttpClient returns an Observable
, if you are not subscribing, i.e. if you are not doing something like this:
getUsers().subscribe((data) => {
console.log('whatever');
})
The http request will never be send, that's how observable works, they only get "executed" when someone is "listening"
CodePudding user response:
Seeing how you try to pass id
as pathVariable your endpoint should also accept it as such. For that refactor your endpoint. Frontend looks fine.
@PutMapping("/api/users/{id}")
public Employee changeStatus(@PathVariable Long id)
{
Employee newEmployee = userRepository.getById(id);
newEmployee.setStatus("Checked");
return userRepository.save(newEmployee);
}
Remove one extra id
from url.
public changeStatus(id: number): Observable<any>
{
const url = this.apiServerUrl /users/ id;
return this.http.put<any>(url);
}
Otherwise try to get rid of any
types and use strong typing - that's the benefit TypeScript gives us.