Search code examples
angularcomponents

How to share a number property between 2 components in angular without relationship (via service only)?


I need to share a property which is a number between two components that aren´t child/parent relationed. I need a true example of how to do it. For now, the property is only in one component, so I also need to know how to send data between then. I will not use things like click, I want to know if I can send the change when a function changes the value;

for example:

component A has a number (monthValue) - component A has a function

setMonthValue(){
    this.monthValue = x;
}

How can both components (A e B) share this value? I need to receive/read this value in B;


Solution

  • One possible way is to use a BehaviorSubject in a shared service.

    private monthValueSubject = new BehaviorSubject<number>(-1);
    

    The good thing about a shared service's BehaviorSubject is that it will retain it's value so any time a new subscription is made it will get the latest value.

    import { Injectable } from "@angular/core";
    import { Observable, BehaviorSubject } from "rxjs";
    
    @Injectable()
    export class SharedService {
      private monthValueSubject = new BehaviorSubject<number>(-1);
    
      constructor() {}
    
      setMonthValue(x: number) {
        this.monthValueSubject.next(x);
      }
    
      getMonthValueObservable(): Observable<number> {
        return this.monthValueSubject.asObservable();
      }
    }
    

    This simple service can have two methods that will let you update the month value.

    Inside your components two basic things are required.

      ngOnInit() {
        this.sharedService.getMonthValueObservable().subscribe(x => {
          this.monthValue = x; // <-- this is where you get new values
        });
      }
    
      setMonthValue(x: number) {
        this.sharedService.setMonthValue(x); // <-- this is where you set new values
      }
    

    Check this working stackblitz.