Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing data between components in Angular: do we always need Observables?

Tags:

angular

I am new to Angular and I am trying to figure out what the best / correct technics are to share data between components with no direct parent / child relationship.

There is already a lot of questions around this topic but they all point towards Observables / rxjs / subjects, etc.

However, in my test app I simply created a service that holds a value and 2 components. In component A, you can update the value defined in the service. Component B reads this value and hence gets the updated value. It works fine as the 2 components get the right value.

There is certainly something I did not grasp yet around the benefits of using those Observables.

Appreciate any insight on this.

like image 270
britsy83 Avatar asked Nov 26 '25 06:11

britsy83


1 Answers

Heretic Monkey is correct but let me show you how easy it is to implement an observable.

@Injectable({
  providedIn: 'root'
})
export class MyState { // I call this file a 'state' instead of a service because it does not get injected the same way
  // don't use any there should be a valid type. I'm initializing my any type to null for this example but IRL I wouldn't do that unless it makes sense.
  private readonly _value = new BehaviorSubject<any>(null);
  // a behavior subject is a subject that starts with an initial value and will emit any changes to that value instantly to any component hooked to it. it's the easiest one to use.
  public readonly $value = this._value.asObservable();

  // this is a getter so you can get a 1 time view of what it is set to (right now it's null)
  public get value$() {
    return this._value.getValue();
  }

  // this allow you to change or mutate your observable and emit that change to your subscribers
  public set value$(val: any) {
    this._value.next(val);
  }

That's how you implement the service/state whatever you prefer to call it.

In your component you can use the ngOnInit life cycle hook to subscribe to it like so:

constructor(private state: MyState) {}

private initSubscriptions(): void {
  this.state.$value.subscribe((val) => {
    this.yourComponentValue = val;
});

You can update your value in the component like so:

this.state.value$ = newValue;
like image 117
Mickers Avatar answered Nov 28 '25 03:11

Mickers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!