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

The element type is not valid: it should be a string for built-in components or a class/function for composite components, but it is currently an object in a React project

In the process of developing a React app to explore MUI capabilities, I encountered an error in my browser: The issue reported is: Element type is invalid - expected a string (for built-in components) or a class/function (for composite components), but rec ...

Generate a new core element featuring the top 10 users

In my app, I have a function that sorts users in the mobile_user table based on their earned points and assigns them a rank. This function is triggered every time an http request is made. Now, what I want to achieve is creating a new root node called lead ...

What could be the reason behind the child component updating without triggering a re-render in Reactjs?

I am encountering an issue with my main component and child chart component. Even though the main component updates the state of the child chart component upon connecting to a websocket, the chart does not redraw as expected. Interestingly, when I click on ...

Validating React Typescript Props: Ensuring that two specific props do not exist simultaneously

Currently, I'm developing a reusable component in React-Typescript and I am looking to validate my props OnClick and component as follows: Both onClick and component prop are optional. These props will only be passed to the component if they need to ...

Conceal the ::before pseudo-element when the active item is hovered over

Here is the code snippet I am working with: <nav> <ul> <li><a href="javascript:void(0)" class="menuitem active">see all projects</a></li> <li><a href="javascript:void(0)" class="menuitem"> ...

What is the optimal method for organizing MongoClient and express: Should the Client be within the routes or should the routes be within the client?

Which is the optimal way to utilize MongoClient in Express: placing the client inside routes or embedding routes within the client? There are tutorials showcasing both methods, leaving me uncertain about which one to adopt. app.get('/',(req,res) ...

There appears to be an issue with the error handling function within React

I am facing an issue with my error function while checking the browser error, and I am unsure why adding a console.log with the error is causing trouble. I need some assistance in troubleshooting this problem which seems to be occurring at line 29 of my im ...

Sharing NPM Scripts Via a Package to be Utilized by Project upon Installation

I have streamlined my linting setup by consolidating all configuration and related packages/plugins/presets (for prettier, stylelint, eslint, commitlint) into an npm package. This allows me to utilize the same setup across multiple projects, simply extendi ...

Using ReactJS and react-router to exclude the navigation menu on the login page

I have a LoginPage designed like this: After logging in, you will be directed to this page: Now, I want the login page to have no navigation and look like this: How can I achieve that? In my App.js, I have the following code: import React, { Component ...

Managing updates with the spread syntax: Dealing with undefined or null properties

Let's take a look at this example method: GetCustomerWithPoints(customerId: number): Customer { const customer = this.customerService.getCustomer(customerId); const points = this.pointService.getPointsForCustomer(customerId); return {...custo ...

Dealing with special characters in Mustache.js: handling the forward slash

I have a JSON file that contains information about a product. Here is an example of the data: { "products": [ { "title": "United Colors of Benetton Men's Shirt", "description": "Cool, breezy and charming – this s ...

How can I obtain an array using onClick action?

Can anyone help me figure out why my array onClick results are always undefined? Please let me know if the explanation is unclear and I will make necessary adjustments. Thank you! Here is the code snippet: const chartType = ["Line", "Bar", "Pie", " ...

Serving static files in Next.js with specific extensions without triggering a download

I'm facing an issue where I need to serve the stellar.toml file in domain/.well-known/stellar.toml with the content type as text/plain. The current configuration works only when the stellar file is saved without an extension. It is essential for me t ...

Using Angular 2, how to filter a single column based on multiple values?

If I have an array of objects as shown below [ {name: 'aaa', type: 'A'}, {name: 'bbb', type: 'B'}, {name: 'ccc', type: 'A'} .... ] I want to build a filter in Angular that displays ...

Do constructors in TypeScript automatically replace the value of `this` with the object returned when using `super(...)`?

I’m having some trouble grasping a concept from the documentation: According to ES2015, constructors that return an object will automatically replace the value of “this” for any instances where “super(…)” is called. The constructor code must ...

Injecting environment variables into webpack configuration

My goal is to set a BACKEND environment variable in order for our VueJS project to communicate with the API hosted there, but I keep receiving an error message saying Unexpected token :. Here is the current code snippet from our config/dev.env.js, and I&a ...

Simulate a failed axios get request resulting in an undefined response

I'm having an issue with my Jest test mock for an axios get request, as it's returning undefined as the response. I'm not sure where I might be going wrong? Here is the component with the axios call: import {AgGridReact} from "ag-grid- ...

Endure the class attribute in Angular 5

My SearchComponent has a route (/search) and SearchDetailComponent has a route (/search-detail:id). In the SearchComponent, there is a searchbox (input field) where I can type any text to start a search. After loading the search results and navigating to ...

"Encountered a problem when trying to import stellar-sdk into an Angular

Our team is currently working on developing an app that will interact with the Horizon Stellar Server. As newcomers in this area, we are exploring the use of Angular 8 and Ionic 4 frameworks. However, we have encountered difficulties when trying to import ...

waiting for udp response in node.js using express

Currently, I am diving into the world of node.js programming and have encountered a challenge. While working with express, I came across an issue. When a POST request is made, it triggers a radius authentication process over UDP using the dgram module. Ho ...