1

I was searching what is the best way to send messages between components in dart-angular applications, and I was kind of confused. I found that in old versions, I would use ScopeAware, as shown in this question: Angular Dart component events, but now this was replaced to Streams.

It seems to me that ScopeAware created a "global" way of managing events between components not directly related, right? Using streams, how can I do create this context?

I have this code, to work with "global" events:

class PostEvent {


  final StreamController<ComponentEvent> _onEventStream = new StreamController.broadcast();
  Stream<ComponentEvent> onEventStream = null;

  static final PostEvent _singleton = new PostEvent._internal(); 

  factory PostEvent() {
       return _singleton;
  }

  PostEvent._internal() {
       onEventStream = _onEventStream.stream;
  }

  onEvent(ComponentEvent event) {
    _onEventStream.add(event);
  }  

}

In my project, I have this structure of components:

Home
  -> Products
    -> Product Item 
  -> Header
    -> Cart Products Count

When one product is add or remove, "Cart Products Count" should be notified. My code, in this case, is a good idea?

Thanks!

Ricardo Bocchi
  • 1,551
  • 2
  • 12
  • 12

1 Answers1

3

Using a stream is a good idea. Now make this class a service, provide it at the root injector and inject it where you want to get notified about updates and subscribe there.

There there are more than one subscriber you need a multicast stream.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • I already do this, I did not put the complete code. My question was whether this is the best form for this context. – Ricardo Bocchi Nov 16 '18 at 12:07
  • 1
    There is not really another way, except perhaps for the special cases parent-child and direct siblings where other variants can be used (based on data-binding), but for the general case a shared service with streams is the way to go. – Günter Zöchbauer Nov 16 '18 at 13:10
  • 1
    Btw. Angular services are singletons by default, you shouldn't add explicit code to make services singletons. – Günter Zöchbauer Nov 16 '18 at 13:11