Double up on your calls to the subscribe function in Angular to ensure successful login

Within my angular 7 application, there is a sign in component that triggers the sign in function within the authentication service. This function initiates an HTTP post request and then subscribes to the response. My goal is to have both the auth service function and component function subscribe to it so that if incorrect credentials are entered, the component can notify the user and display a loading spinner while waiting for the request to complete.

Sign in component:

 onSignIn() {
    if (this.signinForm.invalid) {
      return;
    }
    this.failedSignIn = null;
    this.isLoading = true;
    this.authService.signin(this.signinForm.value.email, this.signinForm.value.password);
    this.isLoading = false;

  }

Sign in function in Auth service:

 signin(email: string, password: string) {
    const signinData = {email: email, password: password};
       this.http.post<{userEmail: string, userId: string, token: string, refreshToken: string, expiresIn: number, userType: string }>(URL + 'signin', signinData).subscribe(response => {
        // Additional operations here
      });
  }

Ultimately, my desired approach is:

  onSignIn() {
    if (this.signinForm.invalid) {
      return;
    }
    this.failedSignIn = null;
    this.isLoading = true;
    this.authService.signin(this.signinForm.value.email, this.signinForm.value.password).subscribe(res => {
    this.isLoading = false;
    this.isAuth = res.isAuth;
});
  }

Answer №1

To simplify things, you can return the observable from the authentication service and then subscribe to it in the component. If there are additional actions you need the service to perform, consider creating a function within the authentication service that can be called during subscription from the component.

It is not recommended to attempt subscribing to an HTTP call in multiple locations (if even possible).

Authentication Service

login(email: string, password: string) {
   const loginData = {email: email, password: password};
   return this.http.post<{userEmail: string, userId: string, token: string, refreshToken: string, expiresIn: number, userType: string }>(URL + 'login', loginData);
} 

performActions(){/*perform necessary actions*/}

Component

onLogin() {
   if (this.loginForm.invalid) {
      return;
   } 
   this.failedLogin = null;
   this.isLoading = true;
   this.authService.login(this.loginForm.value.email, this.loginForm.value.password)
      .subscribe(res => {
          //any additional actions
          this.authService.performActions();
          this.isLoading = false;
          this.isAuthenticated = res.isAuthenticated;
      });
}

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

Implementing Bootstrap 5 within Angular 14 and incorporating SCSS styling

Currently, I am in the process of integrating Bootstrap 5 into my Angular 14 project, which utilizes SCSS instead of CSS. After successfully installing Bootstrap via npm (npm install bootstrap --save), the package is properly listed in my package.json file ...

The expected function is being executed, yet none of the inner functions are invoked

Currently, I am working on unit tests for an Angular application using Jasmine and Karma. One particular unit test involves opening a modal, changing values in a form, and saving them. Everything goes smoothly until it reaches the promise inside the open() ...

"Losing focus: The challenge of maintaining focus on dynamic input fields in Angular 2

I am currently designing a dynamic form where each Field contains a list of values, with each value represented as a string. export class Field { name: string; values: string[] = []; fieldType: string; constructor(fieldType: string) { this ...

Exploring the power of chaining multiple subscriptions in RxJs 6

I have a project using Angular 6, and I'm currently in the process of upgrading rxjs to version 6. In the previous iteration of my app, there was a specific flow where I needed to make sequential calls to observables: 1. Call an observable 2. Perfor ...

The error message indicates a compatibility issue between parameters 'r' and 'a'

Attempting to reproduce the code found in this blog post, but encountering some perplexing errors. import { option, identity, apply } from 'fp-ts'; import type { Kind, URIS } from 'fp-ts/HKT'; import { pipe } from 'fp-ts/lib/functi ...

Measuring Feedback: Utilizing Angular 4 to calculate review ratings

I'm facing a challenge while working on a review form using Firebase and Angular 4. The issue is with calculating the total length of added reviews and the sum of their ratings. Each time a new review is submitted, it gets pushed to a list of objects ...

"Acquiring the version number in Angular 5: A step-by-step

How can I retrieve the version from my package.json file in Angular 5 project? I am using Angular-Cli: 1.6.7 and npm 5.6.0 Here is a snippet from my enviroment.ts file: export const enviroment = { VERSION: require('../package.json').versio ...

Transmit information using express handlebars in a straightforward node application

Struggling to pass data from express handlebars to index.html? Check out my code below: server.js code: const express = require('express'); const app = express(); const expressHandlebars = require('express-handlebars'); const path = r ...

Calling gtag("event") from an API route in NextJS

Is there a way to log an event on Google Analytics when an API route is accessed? Currently, my gtag implementation looks like this: export const logEvent = ({ action, category, label, value }: LogEventProps) => { (window as any).gtag("event&quo ...

Retrieve the attributes associated with a feature layer to display in a Pop-up Template using ArcGIS Javascript

Is there a way to retrieve all attributes (fields) from a feature layer for a PopupTemplate without explicitly listing them in the fieldInfos object when coding in Angular? .ts const template = { title: "{NAME} in {COUNTY}", cont ...

Issue during deployment: The type 'MiniCssExtractPlugin' cannot be assigned to the parameter type 'Plugin'

I'm working on deploying a Typescript / React project and have completed the necessary steps so far: Created a deployment branch Installed gh-pages for running the deployed application Added a deploy command as a script in the package.j ...

The "rest" variable is automatically assigned the type of "any" because it lacks a specified type and is used within its own initializer

Attempting to set up a private route using react router 4 and Typescript. Check out the code I'm working with: type CustomRouteProps<T> = T & { component: any, authRequired: boolean }; function PrivateRoute({ component: Component, authRequ ...

Implement a call feature using ReactJS

My service method involves making a PUT call to an API with an ID parameter. However, I am facing issues with hitting the .put URL. Can someone please verify if this is the correct approach? ENDPOINTS = { SAMPLE: "/sample", }; Below is my ...

What's the reason behind the absence of the bar chart in this presentation?

I need help making a bar chart using d3 and Angular(in VSCode). The x-axis doesn't seem to work properly. Can anyone assist me with this issue? Currently, only the y-axis is displaying without any additional response. I've been stuck on this prob ...

Unable to establish breakpoints in TypeScript within VS Code

I seem to be facing an issue while trying to set breakpoints in my TypeScript nodejs app using Visual Studio Code. Despite following the guidelines provided on the Visual Studio Code website, I have not been able to achieve success. Below is the content o ...

Is it possible for a conditional type in TypeScript to be based on its own value?

Is it possible to use this type in TypeScript? type Person = { who: string; } type Person = Person.who === "me" ? Person & Me : Person; ...

Eslint is unable to locate file paths when it comes to Solid.js tsx extensions

Whenever I attempt to import TSX components (without the extension), Eslint raises an error stating that it's unable to resolve the path: https://i.sstatic.net/NiJyU.png However, if I add the TSX extension, it then prompts me to remove it: https:// ...

What is the proper way to invoke a child method after converting an object from a parent class to a child class?

When we have a subclass B that overrides a method from its superclass A in TypeScript, why does calling the method on an instance of A result in the parent class's implementation being called? In TypeScript, consider a class called Drug with properti ...

Ways to simulate an initialized class within a function without using dependency injection

Creating a unit test for a service that utilizes aws-sdk to retrieve all files from an s3 bucket poses a challenge. Within the function, the S3 class is instantiated and listObjectsV2 is used to fetch files from the bucket. For testing purposes, it's ...

`Where can I find both the old and new values in Angular mat-select?`

Hello there. I am currently working with Angular 6 and Angular Material. I have an array of strings that I am displaying in a dropdown field using mat-select. I need to be able to track the previous value and the new value when a user selects different ele ...