Jack
Jack

Reputation: 1

Call method between independent components using BehaviorSubject in Angular 4+

What is the best practices for calling a method between independent (no parent-child relation) components? I have a look at several samples on the web i.e. but some of them use BehaviorSubject, some of them Observable, and some of them lack of completing observables with ngOnDestroy() method. There is an example usage on How to execute a function from another component that is NOT a sibling of the first component? that I can apply to my Angular7 project successfully, but I think there is a better approach using BehaviorSubject without any missed point. Any idea?

Upvotes: 1

Views: 860

Answers (1)

Jesse
Jesse

Reputation: 2597

Definitely the best-practice approach is to use a shared service as is mentioned in the article. You don't necessarily have to use a BehaviorSubject. You could use regular Subjects if you want, or even more classic getters and setters if that's more familiar to you (although I highly recommend embracing the reactive approach using RxJS).

Services are typically created as singletons, so you will have the issue with long-running Observables unless you put in some custom logic for it (for example, create a method in the service for unsubscribing and call that method on either of the component's onDestroy hook).

I may be misunderstanding your question, but if you're concerned about exposing BehaviorSubjects, you can always wrap them in an Observable and just expose the Obsevable:

private myBehaviorSubject = new BehaviorSubject<boolean>(false);
myObservable = this.myBehaviorSubject.asObservable()

Hopefully that answered your question.

Upvotes: 1

Related Questions