abhilash reddy
abhilash reddy

Reputation: 1586

Is it a bad approach to share data between components using services

I have 2 components, let's say 'A' is parent & 'B' is child. Currently in my application if I have a parent child relation for sharing data among them I pass data through input to the child. But suddenly the requirement changes and 'B' Component wont be a child of 'A' and it would its sibling. Still 'B' Component depends on 'A' Components data. When I moved component B I made the following changes:

  1. Earlier Component 'A' didn't have output event emitter. Now I have output event which emits data to parent.
  2. The Common parent passes data emitted from Component 'A' to 'B' through input.

My question is: would it be bad approach if I share data between components using services even if they have parent child relation. (Even if component relation changes I need not worry about passing data).

Upvotes: 0

Views: 88

Answers (1)

Chund
Chund

Reputation: 459

Typically this is a absolutely fine way to do things. The only thing that can become troublesome for you is syncronisation. If for whatever reason you have Components 'A' and 'B' open on the same time and they manipulate the same data in a service you would need to inform the other component about that change.

A typical approach I have seen a lot would look something like the following:

@Injectable()
export class DataShareService {
  private _data: Subject<MyDataStructure>;
  data$: Observable<MyDataStructure> = this._data.asObservable();

  changeDataTo(changedData: MyDataStructure) {
    this._data.next(changedData);
  }
}

And have 'A' and 'B' subscribe to data$. This way both would be updated by any change and the service itself is responsible for how the data gets communicated, and nothing more, which in my eyes perfectly reflects its job.

Upvotes: 1

Related Questions