Reputation: 1600
When I click it, it adds the data, but when I refresh the page, I can see that it was added. Deleting like this is doing the same problem. I delete, but I can only see that when I refresh the page, it is deleted. How can I solve this situation?
app.component.ts
constructor(private srv: UserServiceService) {}
users: any = [];
checkForm: any;
name: FormControl;
surname: FormControl;
age: FormControl;
async ngOnInit() {
(this.name = new FormControl(
"",
Validators.compose([Validators.required])
)),
(this.surname = new FormControl(
"",
Validators.compose([Validators.required])
)),
(this.age = new FormControl(
null,
Validators.compose([Validators.required])
));
this.getAllUsers();
}
async getAllUsers() {
await this.srv.allUsers().subscribe(val => {
this.users = val;
});
}
addUserFunction() {
this.srv
.addUserService(this.name, this.surname, this.age)
.subscribe(val => {
console.log("val: ", val);
});
this.name.reset();
this.surname.reset();
this.age.reset();
}
async deleteUser(id) {
await this.srv.deleteUserService(id).subscribe(user => {
console.log(user);
});
}
user-service.service.ts
export class UserServiceService {
constructor(private http: HttpClient) {}
allUsers() {
return this.http.get("http://localhost:3000/get_users");
}
addUserService(name, surname, age) {
return this.http.post("http://localhost:3000/add_user", {
name: name,
surname: surname,
age: age
});
}
deleteUserService(id) {
return this.http.delete("http://localhost:3000/delete_user/" + id);
}
}
Upvotes: 1
Views: 58
Reputation: 5632
On successful delete you can filter your user if you don't want to go to the server to fetch a fresh list of users like this:
this.users = this.users.filter(function(index) {
return this.users.id== index;
});
So you can put this to your delete method in subscribe.
Also you can use the same approach on create, just put new user to the list, or fetch fresh ones from the server.
I would suggest that in your create method you return new user which is added to DB and put that object in your array on client side so you can have full object from server in one call.
Upvotes: 1
Reputation: 200
Refresh the data by calling the getAllUsers() method in your component again after deleting/creating a user. Since ngOnInit() only gets called one time after your component is created.
Upvotes: 1