0

i'm trying to perform a login, to make it I use firebase ,the login system work as well , but I'm not able to get the error name from de auth service to my login component. I have tried this :

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('Erreur:',err.message);
      this.setValueError(true);
    });
}

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

And this is my get function

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

And on my login component I got this :

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

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

But the alert returns two values, for example if I make a mistake on my login I got FALSE and TRUE.

I want to get only the trust value, to know if there is a login error.

Thanks for help

chris
  • 2,490
  • 4
  • 32
  • 56
ertyuiooz
  • 1
  • 1

2 Answers2

0

Based on your comment private isError: BehaviorSubject<boolean>, please refer to the accepted answer in this question

Your issue is related to using BehaviorSubject which emits values immediately after a Subscription happens (first FALSE value) and then when login error is detected (TRUE value). You may want to use Subject() instead which holds a single value and it is emitted after subscription (TRUE value when error is detected).

chris
  • 2,490
  • 4
  • 32
  • 56
0

BehaviorSubject should only be used if you have an initial value that will always be output when a subscriber subscribes, even if you haven't called next on the subject yet. For example :

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

This will emit false immediately because a behaviorsubject always has a default value.

What I think you are looking for is a ReplaySubject :

myReplaySubject = new ReplaySubject<boolean>(1);//Store the last 1 error

This works similar to a behavior subject in that it can replay the last emitted values to any new subscriber, but the big difference is is that if no value has been pushed into the subject, the subscribers don't fire.

And just on another side note, A regular old Subject is different again because if you subscribe after next() has been called on a plain subject, you will not be given the value (You only get pumped the messages after you subscribed).

You can read more on Subject vs ReplaySubject vs BehaviorSubject in Angular here https://tutorialsforangular.com/2020/12/12/subject-vs-replaysubject-vs-behaviorsubject/

MindingData
  • 11,924
  • 6
  • 49
  • 68