Get updates on a new subscription for Angular by signing up now

I have a method for authentication that is kept private. Additionally, I have a public method named login which is utilized in my components to carry out the actual login process. I am interested in subscribing to the login method, which internally subscribes to the private authentication method. This will allow me to display loading messages and handle errors uniquely based on different views. Is this achievable?

This is the Authentication method:

private userAuthenticate( email: string, password: string ) {
    return this.httpPost(`${this.baseApiUrl}/auth?format=json&provider=login`, {userName: email, password: password}).subscribe(
        res     => this.saveJwt(res.bearerToken),
        err     => this.logError(err),
        ()      => console.log("Authentication done.")
    );
}

This is the Login method:

login( email: string, password: string ) {
    this.logout();
    return this.userAuthenticate(email, password);
}

I aim to subscribe to the login method to manage loaders and error messages accordingly. I appreciate any assistance.

Answer №1

Don't try to enroll in Subscription (generated by subscribe()). Instead, subscribe to Observable.

If you want an Observable, use map() instead of subscribe(). Then the function calling login() can handle the subscription.

private userAuthenticate( email: string, password: string ) {
    return this.httpPost(
             `${this.baseApiUrl}/auth?format=json&provider=login`, 
             {userName: email, password: password}
           )
           .map(res => this.saveJwt(res.bearerToken));
}

For any additional callbacks needed, consider using the catch and finally operators.

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

Prepending the emulated prefix to Angular 6-7 ViewEncapsulation

Can we customize the tags generated when using ViewEncapsulation.Emulated in an Angular 2-7 component? Currently, it generates tags like [_ngContent-C0], but is there a way to add a custom string to the generated tag, such as [_ngContent-C0-myApp]? Thank ...

How to access the template html in Angular 8 (or 9) before compilation

I'm working on developing a "help center" for my colleagues in the development team, providing guidance on using components and more. My goal is to create a component that displays both the output and the code used to generate it, like this: <app ...

Testing Angular HTTP error handlers: A comprehensive guide

Below, you will find an example of code snippet: this.paymentTypesService.updatePaymentTypesOrder('cashout', newOrder).subscribe(() => { this.notificationsService.success( 'Success!', `Order change saved successfully`, ...

Parsing JSON results in the return of two objects

I am analyzing a JSON file, expecting it to return Message[] using a promise. This code is similar to the one utilized in the Heroes sample project found in HTTP documentation { "data": [ {"id":"1","commid":"0","subject":"test1subject","body":" ...

Retrieve the specific type of property from a generic data structure

I am currently working on a project where I need to determine the type of property within a given Type: type FooBarType { foo: string, bar: number } The function would be structured like this: getType<K extends keyof T>(key: K): string. The ...

Utilizing Typescript Decorators to dynamically assign instance fields within a class for internal use

I am interested in delving into Typescript Decorators to enhance my coding skills. My primary objective is to emulate the functionality of @Slf4J from Project Lombok in Java using Typescript. The concept involves annotating/decorating a class with somethin ...

Before fetching the data from firebase in Angular 2, it is crucial to ensure that the code is properly

I'm facing an issue when trying to retrieve data from Firebase. It successfully retrieves the data, but it takes a few seconds to do so. In the meantime, the code continues running and the variable's value becomes null. Why is this happening? Is ...

Different Categories of Array Deconstruction

While iterating through an array, I am utilizing destructuring. const newArr = arr.map(({name, age}) => `${name} ${age}`) An error occurs in the above code stating: Binding element 'name' implicitly has an 'any' type To resolve th ...

Breaking down types in Typescript: Extracting individual types from an object containing multiple objects

Having a query: const queries = { light: { a... b... }, dark: { a... b... c... d... }, The react element requires a colors parameter that corresponds to one of the themes in the above object, with each theme containing a un ...

Exploring the capabilities of zooming on SVG elements using D3 within an Angular

I want to implement pan/zoom functionality on an SVG element. I came across a tutorial that suggested using d3.js for this purpose, you can find it here Below is the code I have tried: import { Component,AfterViewInit,OnInit } from '@angular/core&a ...

Why is Angularfire2 failing to save the data it fetches?

It seems that I am struggling to accomplish what I need because of a lack of knowledge on the proper method. My goal is to save a connection between a user and a school (which is also a user), and then retrieve some image URLs from the school user in a new ...

Create an object using a combination of different promises

Creating an object from multiple promise results can be done in a few different ways. One common method is using Promise.all like so: const allPromises = await Promise.all(asyncResult1, asyncResult2); allPromises.then([result1, result2] => { return { ...

Angular 7 form does not automatically disable the button upon initialization

My current challenge involves disabling a button until a form is completely filled out. Surprisingly, everything works perfectly in Chrome and Firefox, but IE11 seems to be causing some issues. Below is the relevant code snippet: <div class="col-12"> ...

Exploring nested promises in TypeScript and Angular 2

I have a method called fallbackToLocalDBfileOrLocalStorageDB, which returns a promise and calls another method named getDBfileXHR, also returning a promise. In the code snippet provided, I am unsure whether I need to use 'resolve()' explicitly o ...

Typescript - Error in Parsing: Expecting an expression

I am currently working with Vue and TypeScript and have encountered a problem. How can I resolve it? Here is the code snippet in question: private setTitle(systemConfig: any) { const systemConfigParse; let obj; systemConfigParse = JSON.parse(sy ...

The functionality of two-way data binding seems to be failing in Angular 2

I encountered an issue in my Angular 2 application where I attempted to bind view data using ngModel, but it did not function as expected. event.component.html <div class="form-group"> <label for="comment">About Us:</label> ...

Design an element that stretches across two navigation bars

Currently, I have implemented two Navbars on my website as shown in the image below: https://i.stack.imgur.com/4QmyW.png I am now looking to include a banner that clearly indicates that this site is a test site. In addition, I would like to incorporate a ...

Transitioning React components organized in groups to TypeScript

As I transition my react project to incorporate typescript, one challenge I encountered was adjusting the file structure. In its simplified form, here is how the original js project's file structure looked like: src components index.js inputs butt ...

What is the correct way to utilize the createAsyncThunk function in TypeScript?

You can access the entire project here. I currently have this code snippet: extraReducers: (builder) => { builder .addCase(getTodosAsync.fulfilled, (state, action:any) => { return action.payload.todos ...

Avoiding Bootstrap loading in a Hyperledger Composer application

I am looking to eliminate the Bootstrap stylesheet from my Hyperledger Composer-compiled project. After compiling using yo hyperledger-composer and then running npm start, I noticed that when src/index.html is served at http://localhost:4200/, a Twitter B ...