Angular 10 introduces a new feature where BehaviorSubject can now hold and emit two

Currently, I am attempting to log in using Firebase. The login system is functioning correctly; however, I am facing a challenge in retrieving the error name from the authentication service and displaying it in my login component.

SignIn(email: string, password: string)  {
   this.angularFireAuth
    .signInWithEmailAndPassword(email, password)
    .then(res => {
      console.log('Connected OK');
      this.setValueError(false);
      this.router.navigate(['/user']);
    })
    .catch(err => {
      console.log('Error:',err.message);
      this.setValueError(true);
    });
}

setValueError(newValue): void {
  this.isError.next(newValue);
}

Below is my retrieval function:

getValueError(): Observable<boolean> {
  return this.isError.asObservable();
}

In my login component, I have the following code:

signIn() {
  this.authenticationService.SignIn(this.email, this.password);
  this.authenticationService.getValueError().subscribe((value) => {
    alert(value);
  });

  this.email = ''; 
  this.password = '';
}

The issue I am encountering is that the alert displays two values. For instance, when there is an error in my login, FALSE and TRUE are displayed.

I am seeking assistance on how to only retrieve the actual value indicating whether there is a login error or not.

Thank you for your help

Answer №1

After seeing your code snippet

private isError: BehaviorSubject<boolean>
, I recommend checking out the best answer in this thread

Your issue seems to be connected to the use of BehaviorSubject, which immediately emits values upon subscription (initially FALSE) and then when a login error is detected (TRUE). Consider using Subject() instead, as it holds a single value that is emitted after subscription (switching to TRUE when an error occurs).

Answer №2

In order to utilize a BehaviorSubject effectively, it is essential to have an initial value that will always be emitted when a new subscriber subscribes, even without calling next on the subject yet. For instance:

myBehaviorSubject = new BehaviorSubject<boolean>(false);
myBehaviorSubject.subscribe(x => console.log(x));

With this setup, false is emitted immediately because a BehaviorSubject inherently has a default value.

If you are seeking behavior similar to BehaviorSubject but with slight variations, consider using a ReplaySubject :

myReplaySubject = new ReplaySubject<boolean>(1);//Stores the last 1 item

A ReplaySubject functions similarly to a BehaviorSubject by replaying the last emitted values to any new subscriber. However, unlike a BehaviorSubject, if there are no values pushed into the subject, the subscribers do not receive anything.

Additionally, keep in mind that a standard Subject operates differently - if you subscribe after next() has been called on a plain subject, you will not receive the previously emitted value (messages are only received post-subscription).

For more information on the distinctions between Subject, ReplaySubject, and BehaviorSubject in Angular, check out this resource:

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

Creating your own custom operator using observables is a powerful way

const apiData = ajax('/api/data').pipe(map((res: any) => { if (!res.response) { console.log('Error occurred.'); throw new Error('Value expected!'); } return res.response; }), An enhancement is needed to encapsulate the ...

Monitor events triggered by window.print() and the toolbar in an Iframe

Hey everyone, I need help with the following: Understanding the difference between clicking Print & Cancel when using window.print(). Detecting a print-click originating from an iframe toolbar=1? I've tried the following methods without success: ...

TypeScript failing to correctly deduce the interface from the property

Dealing with TypeScript, I constantly encounter the same "challenge" where I have a list of objects and each object has different properties based on its type. For instance: const widgets = [ {type: 'chart', chartType: 'line'}, {typ ...

Cypress and Cucumber synergy: Experience automatic page reloads in Cypress with each test scenario in the Describe block

Hey, I'm facing an unusual issue. I have a dialog window with a data-cy attribute added to it. In my cucumber scenarios, I have one like this: Scenario: Users open dialog window When the user clicks on the open dialog button I've written Cypre ...

Issue with Angular 8: Struggling to loop through my posts data object

Recently, I embarked on a task that seemed straightforward - creating lists using *ngFor. This snippet showcases the contents of the AppComponent class: import { Component } from "@angular/core"; @Component({ selector: "app-root", ...

The @Hostlistener method consistently returns an 'undefined' value when passing in the @Input() value

I'm encountering an issue where the value from @Input() is undefined in my @Hostlistener method. What could be causing this? export class InputHelpComponent implements OnInit { isOpened: boolean = false; @Input() field!: string; @HostListener(& ...

Missing expected property in TypeScript casting operation

I recently came across this intriguing playground example outlining a scenario where I attempted to convert an object literal into an object with specific properties, but encountered unexpected results. class X { y: string; get hi(): string { ...

Angular tests are not reflecting HTML changes when there is a modification in the injected service

I'm currently testing a component that dynamically displays a button based on the user's login status. The user details are obtained from a service method, and the component uses a getter to access this information. Inside the component: get me ...

Lock the table header in place as the table content scrolls upward using Angular4

Is there a way to keep the table header fixed in place while the rest of the content scrolls up? Below is a snippet from my .html file: <table class="table sticky-header"> <thead> <tr class="row-hor- ...

Unable to render properly after saving to Firebase

Currently, I am working on developing an express app that creates a Google map using geo coordinates extracted from photos. My goal is to utilize Firebase for storing data related to the images. While my code is functioning properly, I encountered an issue ...

Display the values from form fields in Angular2 after dynamically adding them

I am struggling to output the values of each object in the choices array using console log. Despite being able to display the objects in the choices array, all the values appear empty. Every object is showing as timeZonePicker: "", startTimeInput: "", endT ...

Error message: Issue with AWS Serverless Lambda and Angular - TypeError: express function not defined

I'm encountering an issue when trying to deploy my application from localhost:4200 to AWS serverless Lambda. The error in cloudwatch logs is causing a 500 {"message": "Internal server error"} response when I access the URL. My understanding of AWS is ...

Are there any modules in Angular 8 that are used across various projects?

I am facing a challenge with managing two projects that share the same core functionality. These projects have identical layouts and pages, but certain components and modules are specific to each project. Currently, I maintain two separate Angular projects ...

What is the best way to invoke a function in a functional React component from a different functional React component?

I need to access the showDrawer method of one functional component in another, which acts as a wrapper. What are some best practices for achieving this? Any suggestions or insights would be appreciated! const TopSide = () => { const [visible, se ...

Hide Angular Material menu when interacting with custom backdrop

One issue I am facing is with the menu on my website that creates a backdrop covering the entire site. While the menu can be closed by clicking anywhere outside of it, this functionality works well. The problem arises when users access the site on mobile ...

Tips on avoiding issues with the backslash character in Typescript

Can someone help me with creating a regular expression in Typescript that can match the decimal separator character followed by a sequence of zeros in a string? I have tried to come up with an expression as shown below: /\.0+\b/g However, since ...

Data binding with ngModel is contingent on certain conditions

I am facing an issue with conditional data binding using ngModel in Angular4. Let me explain further: I have a small form: <form-question-radio [(ngModel)]="model['q4']" name="question" [options]="[{value:true, label:'Yes'}, ...

How to Customize the Select Dropdown in Angular Material 2

I am having trouble customizing the default style of this component : https://material.angular.io/components/component/select It contains various classes such as .mat-select-placeholder, .mat-select-value However, I cannot find any information in thei ...

Exploring the world of functional programming in Java can be a rewarding experience, especially

I am seeking a method to define generic computation on a data set and have the compiler alert me if there are any errors. Having experience with TypeScript, I have seen that you can achieve something like this: /** * Type inferred as: * Array<{ * ...

An error was encountered at line 7800, character 18 in the three-core.d.ts file in the node_modules/@types/three directory. The error message reads: "Cannot find name 'VRDisplay

I encountered an error in my Angular 6 app while running ng serve ERROR in node_modules/@types/three/three-core.d.ts(7800,18): error TS2304: Cannot find name 'VRDisplay'. node_modules/@types/three/three-core.d.ts(7801,23): error TS2304: Canno ...