Search code examples
angulartypescriptauthenticationservice

How to pass an updated variable to another component without reloading the component?


I am not sure whether such question exists because I dont exactly know what the concept I am looking for is named by. So I have a shared-service:

// shared.service.ts
public showLoginForm: boolean = true;

In my app.component I use the variable from above as follows:

//app.component.ts
ngOnInit: void {
    this.showLoginForm = this.sharedSrv.showLoginForm;
}

Now, in my login.component I change the variable in my service without leaving the app.component view:

// login.component.ts
login(f: ngForm){
...

this.sharedSrv.showLoginForm = false;
}

How do I pass the new value of showLoginFormto the app component?


Solution

  • Make showLoginForm as an Observable stream something like shared.service.ts

        private showLoginFormSubject: BehaviorSubject<boolean>;
    
      constructor() {
        this.showLoginFormSubject = new BehaviorSubject(true);
      }
    
      setShowLoginForm(show: boolean) {
    
        this.showLoginFormSubject.next(show);
      }
    
      getShowLoginForm(): Observable<boolean> {
        return this.showLoginFormSubject.asObservable();
      }
    

    now in the component: login.component.ts

    this.sharedSrv.getShowLoginForm().subscribe(val=>this.showLoginForm=val);
    

    to update the value:

    this.sharedSrv.setShowLoginForm(false);