What is the best way to implement switchMap when dealing with a login form submission?

Is there a better way to prevent multiple submissions of a login form using the switchMap operator?

I've attempted to utilize subjects without success. Below is my current code.

import { Subject } from 'rxjs';
import { Component, Output } from '@angular/core';

private submitStream = new Subject<Event>();
@Output() observ = this.submitStream.asObservable();

formSubmit(event: Event) {
  this.submitStream.next(event);
}

In the HTML, I have the following on button click:

(click)="formSubmit($event)"

How can I achieve the desired functionality without relying on subjects?

The desired behavior should be that only the last submission will be sent to the backend API, cancelling any previous ones when the submit button is clicked multiple times.

Answer №1

After some troubleshooting, I managed to solve the issue by implementing the following code snippet within the constructor:

this.submitStream.pipe(switchMap(() => this.authService.login(this.f.username.value, this.f.password.value)))
        .subscribe((result) => {
            this.router.navigate(['dashboard']);
        }, (err) => {
            this.error = err;
            this.modalService.showSnackError(err.error.message);
        });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing HttpClient in a static method service with Angular

One of my services contains a static method that I use for some initialization treatment. Within this method, I need to retrieve data from a web service @Injectable() export class FeaturesInitializationService { static allowedFeaturesModul ...

Interacting between components using Angular 2 services

I am attempting to implement bidirectional service communication using Angular. I have followed the instructions provided in the documentation here: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service interactio ...

Utilizing AJAX in jQuery Mobile for Collapsible Content

I am currently generating a variable number of these elements using a foreach() loop: <div id="<?php echo $data['id']; ?>" data-role="collapsible" data-theme="a"> <h1 style="white-space: normal"><?php echo $data['te ...

Tips for shrinking a sticky header when scrolling using Angular and JavaScript

Looking for a way to modify the header component in an Angular application so that it shrinks as the user scrolls down while maintaining its sticky functionality. How can I adjust the display of the lower half of the header to show no text when the user s ...

Updating parent components through child components in ReactWould you like another unique

In my current project, I am attempting to change the state of the main component labeled App.tsx by using a child component called RemarksView.tsx. I have attempted passing props such as setRemarks and remarks, but unfortunately the state in the parent c ...

Exploring the object structure received from AngularFire

Here is the Firebase query that I am running: var ref = new Firebase('https://<myfirebase>.firebaseio.com/companies/endo/status'); data = $firebaseObject(ref); console.dir(data); The object that I receive looks like this: d ...

The functionality for inserting data via Ajax in WordPress is failing

Greetings, I am currently in the process of developing a popup plugin for WordPress that involves inserting data into a database using AJAX. Everything in my code is functioning correctly up until the jQuery section, where the data fails to insert into the ...

The function that was provided as a parameter is not functioning as expected

I have a WsConnector class responsible for connecting to my backend application and subscribing to a WebSocket topic. export class WsConnector { private stompClient: any; connect(onMessage: (msg) => void) { this.stompClient = Stomp.over ...

When running the command `npm install <node_module> --save`, the dependencies are not being updated as

<=== If you're facing the same issue, try reinstalling your computer to fix it ===> I recently had to reformat my computer and set everything up again. After reinstalling Node and NPM, I encountered some problems that are really irritating me. ...

Is there a way to achieve a transparent background while animating the second text?

I am seeking to create a unique typography animation that involves animating the second text, which is colored and consists of multiple text elements to animate. The animation should showcase each text element appearing and disappearing one after the other ...

using node.js to extract a cookie from a 302 redirect

Need help simulating a login using node.js. The request is a post method and returns a 302 status code. However, when trying to simulate the request in node, I encounter the following error: Error handling unrejected promise: StatusCodeError: 302 Upon i ...

Determine the overall cost based on varying percentage increases for each step

I am currently working on developing a price estimation calculator. Here is the breakdown: For 1000 MTU, the price will be 0.035, resulting in a total of 35. For 2000 MTU, the price will be 0.034, making the total 67. For 3000 MTU, the price will be 0.03 ...

Master the art of horizontal scrolling in React-Chartsjs-2

I recently created a bar chart using react.js and I need to find a way to enable horizontal scrolling on the x-axis as the number of values increases. The chart below displays daily search values inputted by users. With over 100 days worth of data already, ...

Challenge encountered while creating a child tag that can be assigned to multiple parent tags

I have an xml format like the one provided. <xml> <parent id="0"> <child type="name"> </child> <child type="age"> </child> </parent> <parent id="1"> <ch ...

What is the reason for the absence of the Access-Control-Allow-Origin response header in .NET Core CORS Policy?

Take a look at the following code snippet: builder.Services.AddCors(options => { options.AddPolicy(name: "MyPolicy", policy => { policy.WithOrigins("http://example.com", ...

What is the best way to showcase the content from multiple uploaded files?

Below is an example demonstrating how to display the contents of a single uploaded file. .js $scope.uploadFilename = function (files) { if (!files[0]) { return; } var reader = new FileReader(); reader ...

JQuery div not cooperating with other JavaScript/jQuery functions

I used the $(select).append() method to add one div inside another div, but I wanted to close it on click of an image. So I added an image and another $(select).button().click( { $(select).hide() }) to achieve this functionality. However, when clicking t ...

When the input value is changed programmatically, the onchange event does not execute as expected

Having trouble updating the content of my dataTable when using JS script to change the quantity value. Here is a snippet from my code. <h:inputText id="counterFeatures" value="#{myBean.quantity}"> <f:ajax event="change" render="myDataTable" ...

Deleting JSON files using Discord and Node.js by requiring them from a specific folder

Currently, I am in the process of developing a Discord bot using Node.js. One of the functions within the bot utilizes JSON files to store information about specific entities. I aim to create a command in Discord that, when called with a specific name asso ...

Adjusting Image Size based on Window Width for Internet Explorer

Based on the provided code snippet <style> .x{ background: url('img.jpg') no-repeat; background-size: contain; height: 100%; } </style> <div class="x"></div> It is functioning correctly in Chrome and Firef ...