I have an Angular app (v17) in an Nx Monorepo. This component is in a library I created. For some reason, when I submit my form, the Http request does not fire. Everything was working until I tried to use a SwitchMap to get the reactive form's data stream into the request. I've poured over docs and examples and can't seem to figure out where I'm going wrong. I should mention as well that this is an SSR/SSG Angular app.
export class SignupFormComponent {
http = inject(HttpClient);
fb = inject(FormBuilder);
headers = new HttpHeaders({ 'Content-Type': 'application/json' });
portalId = 'dummy';
formId = 'dummy';
signUpForm = this.fb.group({
firstName: ['', [Validators.required]],
lastName: ['', [Validators.required]],
email: ['', [Validators.required, Validators.email]],
company: ['', [Validators.required]],
});
dataObject$ = this.signUpForm.valueChanges.pipe(
debounceTime(500),
distinctUntilChanged(),
map((val) =>
Object.keys(val).map((key) => ({
objectTypeId: '0-1',
name: key.toLowerCase(),
value: val[key as keyof typeof val],
})),
),
);
req = this.dataObject$.pipe(
switchMap((data) => {
const url = `https://api.hsforms.com/submissions/v3/integration/submit/${this.portalId}/${this.formId}`;
return this.http.post(url, JSON.stringify(data), {
headers: this.headers,
});
}),
);
submitForm() {
return this.req.subscribe(console.log);
}
}
<form [formGroup]="signUpForm" (ngSubmit)="submitForm()">
<label for="first-name" class="text-white">First Name</label>
<input id="first-name" type="text" formControlName="firstName" />
<label for="last-name" class="text-white">Last Name</label>
<input id="last-name" type="text" formControlName="lastName" />
<label for="email" class="text-white">Email</label>
<input id="email" type="text" formControlName="email" />
<label for="company" class="text-white">Company</label>
<input id="company" type="text" formControlName="company" />
<button type="submit">
Join Now
</button>
</form>
The
valueChangesis a good option when we subscribe to it during the form initialization, since we havedistinctUntilChangedpresent and there are no value changes after the form is submitted thePOSTis never called, to simplify this use case, we can just manually contruct the request object using the same logic you wrote and then call the api!stackblitz