Here I have two methods, create and update, that send data to an API. I am looking to enhance the createUser and updateUser methods as they are very similar.
Additionally, if you have any suggestions on a better way to directly set the id property as nullable from the router and differentiate between editing and creating a client without using this.isAddMode.
export class ClientFormComponent implements OnInit {
registerForm: FormGroup = new FormGroup({});
isAddMode = false;
constructor(
private formBuilder: FormBuilder,
private snackBar: MatSnackBar,
private route: ActivatedRoute,
private router: Router,
private clientService: ClientService
) {}
ngOnInit(): void {
console.log(this.route.snapshot.params["id"]);
this.isAddMode = !this.route.snapshot.params["id"];
console.log(this.isAddMode);
// [...]
if (!this.isAddMode) {
this.clientService
.getById(this.route.snapshot.params["id"])
.pipe(first())
.subscribe((x) => this.registerForm.patchValue(x));
}
}
onSubmit(): void {
// stop here if form is invalid
if (this.registerForm.invalid) {
return this.openSnackBar("Invalid form");
}
console.log(this.registerForm.value);
if (this.isAddMode) {
this.createUser();
} else {
this.updateUser();
}
}
// [...]
private createUser() {
const data = {
name: this.registerForm.value.name,
organization: this.registerForm.value.organization,
location: {
address: this.registerForm.value.address,
zipCode: this.registerForm.value.zipCode,
city: this.registerForm.value.city,
},
contacts: {
phone: "+33" + this.registerForm.value.phone,
email: this.registerForm.value.email,
site: this.registerForm.value.site,
},
};
this.clientService
.create(data)
.pipe(first())
.subscribe({
next: () => {
this.openSnackBar("Successfully added");
this.router.navigate([""], {
relativeTo: this.route,
});
},
error: () => {
this.openSnackBar("Invalid form");
},
});
}
private updateUser() {
const data = {
name: this.registerForm.value.name,
organization: this.registerForm.value.organization,
location: {
address: this.registerForm.value.address,
zipCode: this.registerForm.value.zipCode,
city: this.registerForm.value.city,
},
contacts: {
phone: "+33" + this.registerForm.value.phone,
email: this.registerForm.value.email,
site: this.registerForm.value.site,
},
};
this.clientService
.update(this.route.snapshot.params["id"], data)
.pipe(first())
.subscribe({
next: () => {
this.openSnackBar("Successfully updated");
this.router.navigate([""], {
relativeTo: this.route,
});
},
error: () => {
this.openSnackBar("Invalid form");
},
});
}
}