Home > Software design >  How to show the changes after submitting the form
How to show the changes after submitting the form

Time:10-26

I have a field in service (loginService) isLogged, it is a behavoiorSubject

public isLogged = new BehaviorSubject<boolean>(!!localStorage.getItem('authToken'));

When I submit the form on login.component, onSubmit() method works and it change the value of isLogged to true.

public onSubmit() {

  if (this.user.valid) {
    this.loginService.isLogged.next(true);
  }
}

I want to show the isLogged value in header.component.html so I use async pipe in view but its value doesn't change in header.component.html when I submit the form.

<div (click)="loginBtnClick()" routerLink="login"> <span>{{loginService.isLogged | async}}</span></div>

enter image description here

enter image description here

enter image description here

enter image description here

What am I doing wrong here?

CodePudding user response:

You should define a BehaviorSubject in a separate injectable class(service) after that you have to inject that service to both components whether you want to set value or read value.

CodePudding user response:

  • Please do not post code as embedded pictures. If the external service hosting them goes down, your question becomes possibly indecipherable.

  • You're attempting to execute statements after router.navigate(...) which might never be executed. Instead you have 2 options:

    • Trigger router#navigate after the statements
    this.loginService...;
    this.loginService...;
    this.loginService...;
    this.router.navigate(['../main']);
    
    • router#navigate function returns a promise. So you could execute the statements in it's then block.
    this.router.navigate(['../main']).then(() => {
      this.loginService...;
      this.loginService...;
      this.loginService...;
    });
    

CodePudding user response:

I found the solution, service was provided in the lazy loaded module so it does not act like singleton, so I moved it to coreModule and it works!

  • Related