0

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?

2
  • 1
    You need to use a BehaviorSubject to watch for changes to that service variable. You can then subscribe to those changes within your component. This is a good answer stackoverflow.com/questions/51545856/… Commented Sep 22, 2020 at 17:41
  • Thank you for sharing a helpful link! Commented Sep 22, 2020 at 17:57

1 Answer 1

0

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Now, I really understood how BehaviorSubject works!
There are a few typos in the code. will edit it now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.