Currently, I have a form where new members can be added. Upon submitting the form, it is crucial to ensure that the email entered for the new user is not already in use. If the email is already associated with an existing member, an alert will pop up displaying the message: "Email is already in use!". On the other hand, if the email is unique, the user will be redirected to another view and an alert-success will be shown. The challenge I am facing is that when calling the service method to check if a new member has been created, the function returns the member undefined before it is properly filled in the subscription. Does anyone have any ideas on how to manage this situation and ensure that the subscribe is executed before the return?
Service Method:
postMemberContactInfo(memberContactInfo: MemberContact){
this._http
.post<MemberContact>(this._membersUrl, memberContactInfo, {
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
responseType: 'json',
observe: 'body',
})
.subscribe({
next: (value) => { this._newMember = value },
complete: () => { this.router.navigate([`/members/${this._newMember.id}`], {
state: this._newMember
} ) },
error: (error) => catchError(this.handleError)
})
return this._newMember;
}
Component TypeScript:
onSubmit() {
if (this.addMemberForm.invalid) this.addMemberForm.markAllAsTouched();
else {
let postedMember = this.memberAddService.postMemberContactInfo({
name: this.getOrElse("name", ""),
surname: this.getOrElse("surname", ""),
role: this.getOrElse("role", ""),
email: this.getOrElse("email", ""),
username: this.getOrElse("username", ""),
comments: this.getOrElse("comments", ""),
});
if (postedMember == undefined) this.showAlert = true;
else {
this.showAlert = false;
this.newMemberCreated.emit(postedMember);
}
}
}
Template:
<app-generic-alert
[ngClass]="showAlert ? 'd-block' : 'd-none'"
[alertType]="'alert-danger'"
[mainMessage]="'ERROR: '"
[secondaryMessage]="'Email is already in use!'"
(closeAlertEvent)="closeAlertHandler()"
></app-generic-alert>