Angular 2 Authentication Service powered by Reactive Extensions

I am currently working on a login form component that includes the following:

login.component.ts

ngOnInit() {
    this.authenticationService.loginAttempt
        .subscribe(() => this.onSuccess(), err => this.onError(err));
}

login(credentials) {
    this.authenticationService.attempt(credentials);
}

In my authentication service, I have the following setup:

authentication.service.ts

class AuthenticationService {
    loginAttempt = new Observable<>();
    credentials = new Subject<Credentials>();

    constructor(private userService: UserService) {
        this.loginAttempt = this.credentials
            .flatMap(credentials => this.makeLoginRequest(credentials);
    }

    attempt(credentials: Credentials) {
        this.credentials.next(credentials);
    }

    private makeLoginRequest(credentials) {
        return this.userService.getTokens(credentials.email, credentials.password);
    }
}

The issue I am encountering is that when a login attempt fails and triggers the onError function in the login.component, subsequent login attempts do not trigger the request due to the previous error. How can I handle errors in the login.component to display an error message while still allowing for retry attempts?

Edit:

This question recommends using retry or retryWhen. However, I am unsure how to implement this based on user interactions when clicking the login button again. What would be the best approach to achieve this?

Answer №1

One way to handle this is by loading it on the ngOnit so that it loads when the page loads initially.

Once loaded, there's no need to reload it again. This ensures that success remains success and error remains error.

Simply place the service call behind the button call and your task is complete.

Edit

Replace:

ngOnInit() {
  this.authenticationService.loginAttempt
    .subscribe(() => this.onSuccess(), err => this.onError(err));
}

With:

buttonClicked() {
  this.authenticationService.loginAttempt
    .subscribe(() => 
      this.onSuccess(), 
      err => this.onError(err)
      );
}

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

Tips for creating a window closing event handler in Angular 2

Can someone guide me on how to create a window closing event handler in Angular 2, specifically for closing and not refreshing the page? I am unable to use window.onBeforeunLoad(); method. ...

Determining the location of the cursor within 'ng2-ckeditor'

I'm a beginner with Angular 2 and I'm using 'ng2-ckeditor 1.0.7' in my Angular 2 application. The editor is functioning well within the app. However, I am now faced with the challenge of appending text at the cursor position. Unfortunat ...

Encountering an unresolved variable issue in Angular 2 rc.1 and PhpStorm 2016.1.2

Ever since I upgraded Angular 2 in my project to rc.1, my IDE, PHPStorm 2016.1. has been having trouble finding many properties and static functions, such as those from the Observable class (rxjs) like Observable.of and Observable.forkJoin. I primarily us ...

Error: Unable to access the 'nativeElement' property because it is undefined - occurring during the ngAfterViewChecked lifecycle hook

I am facing issues with some of my karma jasmine unit tests failing after adding an ngAfterViewChecked. Despite initializing the "mySwitchEl" as shown below, the error persists. @Component({ selector: 'my-component', templateUrl: '. ...

Location website various categories individuals

As I work on creating a website, there are distinct users assigned - Dealers and Workers. Only workers have permission to access the index.html page, while only dealers can access odeme.html. Initially, I set it up such that: index.html=http://localhost:8 ...

Is there a way to access the name of a generic type T class in TypeScript?

I'm currently working on incorporating the Service Locator pattern into my TypeScript project. Below is the snippet of my code: //due to only partial knowledge of TypeScript private static serviceMap: Map<string, any>; public static get& ...

Incorporate a JavaScript script into an Angular 9 application

I have been experiencing issues trying to add a script.js file to angular.json and use it in one component. Adding a script tag directly to my HTML file is not the ideal solution. Can someone suggest an alternative approach or point out what I may be missi ...

Tips for creating a type-safe union typed save method

My goal is to build a versatile http service that includes a method like save(value), which in turn triggers either create(value) or update(value). What sets this requirement apart is the optional configuration feature where the type of value accepted by c ...

Does moment/moment-timezone have a feature that allows for the conversion of a timezone name into a more easily comprehendible format?

Consider this example project where a timezone name needs to be converted to a more readable format. For instance: input: America/Los_Angeles output: America Los Angeles While "America/Los_Angeles" may seem human-readable, the requirement is to convert ...

Creating a unique abstract element for cycling through a collection

I have multiple components that all have a similar structure: import { Component, Input, Output } from '@angular/core'; import { Subject } from 'rxjs'; import { Tag } from 'src/app/models'; @Component({ selector: 'app ...

Managing the closest element depending on the selected option in Angular 5

My task involves accessing the nearest element of a dropdown. The HTML below includes multiple dropdowns and input boxes. When selecting options from the dropdown, I need to enable or disable the input box closest to it. <div class="form-block" *ngFor= ...

Exploring the world of Jasmine and Angular: How to effectively mock nested methods within the Class being tested

Hello esteemed community... I have encountered a perplexing issue that appears straightforward, but has eluded my attempts at resolution... The challenge I am facing involves testing a Controller-Class in Angular. This particular codebase is laden with d ...

How can you initialize a JavaScript class that has a member variable of its own class?

I've come across an interesting puzzle. I am creating a class that can dynamically replicate itself to different levels, similar to an expandable menu. The initial definition looks like this: class MyClass { name: string = ''; fields ...

The impact of placing a method in the constructor versus outside it within a class (yielding identical outcomes)

These two code snippets appear to produce the same result. However, I am curious about the differences between the two approaches and when it would be more appropriate to use one over the other. Can someone provide insight into this matter? Snippet 1: c ...

Deleting the previous ion-view from DOM in Ionic v1 with Angular

I have been working on modifying an app built in Ionic v1. Within the app, there is a primary View titled 'Client's Profile' that contains links to two other Views: Support Request and Complaints. In the Support Request view, there is a Te ...

Creating custom types in Typescript to avoid the "is not assignable to type..." error

Running into a challenge while using the graphql-request module from Prisma Labs. Specifically, I am unsure of how to define certain options using typescript. In my request, there are 2 headers that need to be defined: interface GraphQLHeaders { 'X ...

Experimenting with nested dual dynamic routing within the app's directory

Currently working with NextJS 13 and executing the following operations within the app directory. I am attempting to utilize the generateStaticParams function to generate static pages during build time. The route structure is: subpage/[categoryName]/[gif ...

Solving issues with malfunctioning Angular Materials

I'm facing an issue with using angular materials in my angular application. No matter what I try, they just don't seem to work. After researching the problem online, I came across many similar cases where the solution was to "import the ...

TypeScript overlooking mismatched type arguments in generics

Currently, I am in the process of constructing a pluggable interface/class system that enables an "output" to connect with an "input". To my surprise, TypeScript seems to overlook any warnings or errors that might arise when a compatible interface is pai ...

Understanding the return parameter "typeof SomeClass" in TypeScript

typeof in JavaScript returns a string. The TypeScript typings for Sequelize include return types of typeof Model. What does this mean and what is its purpose? I have looked through the documentation but could not find an explanation. Link to Sequelize Typ ...