0
votes

First question so go easy on me!

I am looking to build a shared service in Angular2 that provides an observable property that can be subscribed to by components in the app.

Also I am looking to set this up so that the data is provided from a component and not via an HTTP get call. I have found examples of setups where it uses the DB as a datasource for CRUD actions, but not where it is an array or object created in the component.

A quick example is as follows:

  1. Service creates observable property at load
  2. Comp1 updates a property on service.
  3. Comp2 (subscribed to observable property on service) receives update from service.
  4. Comp2 continues to get changes as Comp1 continues to make changes to observable property

Does anyone know of a good explanation or have an example of this use case?

Thanks!

1

1 Answers

0
votes

That's pretty common use case, you can do it as follow.

1) In your service constructor initialize observable

this.myObservable = new Subject();

Depending on what you want to achieve you can use different observables. Subject is both Observable and Observer and would return it's latest value on subscription.

2) In your source component push new value

myService.myObservable.next({...});

You can also do it via setter in your service class, so you will be able to modify data before pushing it into stream.

3) In your consumer classes subscribe to stream

myService.myObservable.subscribe(value => ...);

You can subscribe to it in as many components as you want. When you subscribe you will get latest value immediately and then new values on update.

If you want to have initial value, when initializing Observable in service, you can use BehaviorSubject instead of Subject.