I have this code, I guess the switchMap unsubscribes from the one that the map returns; problem is every 2nd click the form submission refreshes the page, so how can I fix it:
import {
AfterViewInit,
ChangeDetectionStrategy,
Component,
ElementRef,
inject,
viewChild,
} from '@angular/core';
import { fromEvent, map, switchMap } from 'rxjs';
@Component({
selector: 'app-root',
standalone: true,
imports: [],
templateUrl: './app.component.html',
styleUrl: './app.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AppComponent implements AfterViewInit {
private _httpClient = inject(HttpClient);
private _formRef = viewChild<ElementRef<HTMLFormElement>>('form');
ngAfterViewInit(): void {
const formRef = this._formRef()!;
const loginFormSubmit = fromEvent(formRef.nativeElement, 'submit').pipe(
map(event => {
event.preventDefault();
const formData = new FormData(formRef.nativeElement);
const username = formData.get('username') as string;
const password = formData.get('password') as string;
return {
username,
password,
};
}),
switchMap(({ username, password }) =>
this._httpClient.post(
'https://dummyjson.com/auth/login',
JSON.stringify({ username, password })
)
)
);
loginFormSubmit.subscribe({
next: response => {
console.log('Login response:', response);
},
error: err => {
console.error('Login error:', err);
},
});
}
}