Incorporating a custom loading message on the login page using Angular

Currently facing an issue with displaying a loading message that is connected to the server response. I was able to implement this successfully for the logout function but am struggling with it for the login function. Below is the code snippet from my account service:

login(email: string, password: string) {
        return this.http
            .post<User>(
                environment.apiUrl + '/auth/login',
                {
                    email: email,
                    password: password
                })
            .pipe(map(user => {
                // Storing user details and JWT token in local storage to maintain logged-in state between page refreshes
                localStorage.setItem('scrb-user', JSON.stringify(user));
                this.userSubject.next(user);
                return user;
            }));
    }

    signup(user: User) {
        return this.http
            .post<User>(
                environment.apiUrl + '/auth/signup',
                user
            );
    }

    

    logout() {
        this.message
            .loading('Action in progress', { nzDuration: 2000 })
            .onClose!.pipe(
                concatMap(() => this.message.success('Loading finished', { nzDuration: 2000 }).onClose!),
                // concatMap(() => this.message.info('Loading finished is finished', { nzDuration: 2000 }).onClose!)
            )
            .subscribe(() => {
                localStorage.removeItem('scrb-user');
                this.userSubject.next(null);
                this.router.navigate(['/account/login']);
                console.log('All completed!');
            });
    }
}

Answer №1

If you want to incorporate a variable in your code, you can follow this example:

login.component.html

//...Your form
<button type="submit" class="btn btn-primary shadow-none" #button>
  <span *ngIf="!this.isLoading">Login</span>
  //Bootstrap Spinner
  <div class="spinner-border spinner-border-sm text-light" role="status" *ngIf="this.isLoading">
  </div>
</button>

login.component.ts

sendLogin(form: NgForm) {
  this.isLoading = true;
  this.loginService
    //Your Login Method (Saved in another file)
    .postLogin(form.value.username, form.value.password)
    .subscribe(
    (data) => {
       this.isLoading = false;
       this.router.navigateByUrl('index');
     },
     (err) => {
       this.isLoading = false;
       alert(err);
     })
     form.reset();
  }
);

}

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

What is the proper way to include special symbols such as "++" and "#" in a request?

I am facing an issue while trying to make a request to an ASP .NET CORE API from an Angular application using Typescript. Upon sending the request, the API searches in an SQL database for any rows with the specified value. The problem arises when attempt ...

What is the best way to declare a minimum and maximum date in HTML as the current date?

I have a question regarding setting the min/max date for a date input in my Angular 6 project. How can I ensure that only dates up to the current date are enabled? So far, I have attempted to initialize a new Date object in the ngOnInit function and set t ...

What are the correct steps for a successful installation of ag-Grid enterprise?

I recently tested some components using the community edition of ag-Grid, but found it lacked support for certain features, such as adding set filters with the SetFilterModule. This meant I couldn't place filter boxes under column headers in the commu ...

Understanding data and custom types in Vue with TypeScript

One of my data types is called "student." export interface Student { name: string, age: number } I am looking to associate this type with a student's information. data() { const tommy: Student = {} return { tommy, } However, I noticed that wh ...

Updating data in MongoDB using a POST request in Angular 2

I am currently working on implementing a post request to update a value in MongoDB. The scenario involves a user inputting a new value (bitcoin) into a form, which triggers the post request upon submission: bitcoinChange(bitcoin){ let headers = new ...

What is the method for reaching a static member of a class within a decorator for a method of the same class?

Upon the release of TypeScript 5.0, the new decorator APIs have been introduced and I am eager to utilize them for automatically providing parameters to a method from a static property within the same class. The decorator parameters and factory are defined ...

Generating formarray instances in Angular using data from MySQL records

I am currently working on a project where I need to populate formcontrols in formarray based on the data retrieved from a MySQL database. However, when I pass the success data from MySQL, I encounter an error that says "Cannot read property 'controls& ...

Encountering an error message stating "Unable to access property 'injector' as null when attempting to downgrade Angular 2 service."

Hello everyone, I could use some assistance with a particular issue I'm facing. Below is the code snippet from my angular 1.x app.js: angular.module('app', []); angular.module('app.test', ['app']) .config(($statePr ...

Is there a way to locate all projects impacted by `nx`?

Currently, I am utilizing the nx tool to manage a mono repo specifically designed for typescript projects. The nx comes equipped with a command called affected, which allows me to focus solely on the changed project and any other projects that rely on it. ...

Recursive rendering of tree components in React

I am facing a challenge in rendering tree items recursively using React. I have been struggling to achieve the desired outcome as calling treeRender(children) seems to alter the data structure when a folder is encountered for the first time. I am curious a ...

Capturing user input with Angular Material forms in HTML

In the process of working on a project in Angular, I am utilizing the Angular Material component library. As part of this project, I am creating a form with multiple fields. Everything is functioning properly, however, the layout appears slightly off: ht ...

The callback in oidc-client-js did not result in any state being returned

Seems like there is an issue specifically with angular 5.2.8 & 6, while it worked fine with angular 5.2.7. I took the initiative to create a ng5 branch and updated angular to the latest 5.2.8 version only to encounter the same error! Could someone pleas ...

Activate individual row Kendo UI Angular 2 grid mouse hover event

I understand that utilizing the template syntax allows me to utilize the standard angular 2 (mouseover) event listener in order to detect a mouse over event for a specific column. I am curious if there exists a method to listen for mouseover events for an ...

The filter() and some() functions are not producing the anticipated output

Currently, I am in the process of developing a filtering mechanism to sift through a dataset obtained from an API. The array that requires filtering contains objects with various parameters, but my aim is to filter based only on specific parameters. For ...

Redux - a method of updating state through actions

Hello, I am currently working on developing a lottery system and I have a question regarding the best approach to modify state using action payloads. Let's consider the initial state: type initialCartState = { productsFromPreviousSession: Product[ ...

Using React Material UI to create multiple collapse components

Currently, I am facing an issue where all the collapses in my list are linked to one state for "open." This means that if I open one list, all the other lists also open. I am looking for a way to keep the collapses separate from each other without needing ...

Can a component's route be dynamically changed based on its state?

Within an Angular 12 application, there exists a component known as SignUpComponent: export class SignUpComponent implements OnInit { form: FormGroup; result: boolean; constructor(private formBuilder: FormBuilder, private userService: UserService) ...

Add a custom design to the Material UI menu feature

I am currently trying to implement a custom theme using the following code: import Menu from '@material-ui/core/Menu'; import { createStyles, withStyles, Theme } from '@material-ui/core/styles'; const myMenu = withStyles( ( theme: The ...

Unlocking the Power of the .data Attribute in Angular's In-Memory Web API

My objective is to seamlessly switch between using in-memory-web-api and a real backend. In the Angular 2 (or 4) Tour of Heroes tutorial, it explains how the server returns data. The in-memory web API example returns an object with a 'data' prop ...

Exploring the New Features of Angular 13 with Typescript, Regular Expressions, and

Currently, I am working on an Angular 13 project and I am trying to create a directive that will only allow users to type numbers and '/' in my date input field format of dd/mm/yyyy. Below is the regular expression (Regx) that I am using: if (!St ...