britsy83
britsy83

Reputation: 73

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

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.

Upvotes: 4

Views: 1004

Answers (2)

Guddu Kumar
Guddu Kumar

Reputation: 1

Service

import { Injectable } from '@angular/core';
    
@Injectable()
export class AppService {
    constructor() {}
    
    name: String;
    
    getVale() {
        return (this.name = 'This is my service data');
    }
}

component where using service

import { Component, Input } from '@angular/core';
    
import { AppService } from './app.service';
    
@Component({
    selector: 'my-app',
    templateUrl: './hello.component.html',
    styleUrls: ['./hello.component.css']
})
export class HelloComponent {
    constructor(private app_service: AppService) {}

    name: String;

    ngOnInit() {
        this.name = this.app_service.getVale();
        console.log(name)
    }
}

Upvotes: 0

Mickers
Mickers

Reputation: 1449

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;

Upvotes: 1

Related Questions