'Angular, subscription and variable update

Studying Angular I've found this problem: when I'm into a subscription and I receive an error from backend, it correctly enters in the ERR part, and prints "fail" in the console, but it change a boolean only the second time I call it.

That's my code:

Template:

{{isAlreadyRegistered}}

<alert *ngIf="isAlreadyRegistered">
  User already registered.
</alert>
...
<div [formgroup]="registerForm">
...
<button (click)="register()">Save</button>

This is TS:

registerForm: FormGroup;
isAlreadyRegistered: boolean = false;

...

register(): void{
this.service.SignUp({body: User}).subscribe(
  (res) => {console.log('success')},
  (ERR) => {
  this.isAlreadyRegistered = true;
  console.log('fail', ERR);
  } 
);
}

I interpolated the boolean variable on the first line to understand how does it works. So for show the <alert> part and let the interpolated boolean changes I have to press the SAVE button twice. And I'm sure it enters in the ERR part because it prints 'fail' in the console twice.

I've tried to make it an Observable instead of a boolean, but it still works only the second time I press it.

So, my question is: why it doesn't change the boolean value the first time I press the button, but prints the console log? And why the second time it works correctly?

Thanks!



Solution 1:[1]

Try this:

inject ChangeDetectorRef into constructor

import { ChangeDetectorRef } from '@angular/core';

  constructor(
    ...
    private cd: ChangeDetectorRef,
  ) { }

and add this.cd.markForCheck(); to a register method

register(): void{
  this.service.SignUp({body: User}).subscribe(
    (res) => {console.log('success')},
    (ERR) => {
      this.isAlreadyRegistered = true;
      console.log('fail', ERR);
      this.cd.markForCheck();
  } 
 );
}

I hope this will fix your issue.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mahdi Rezazadeh