In my Angular2 app, written in Dart, I have several services that track data shared between components that don't necessarily have any particular relation in the view. I need updates initiated by any component to be reflected in every component's display, I want the performance benefits of OnPush
change detection, I need components to display values that may have been set before the component was created, and I want all of this to be accomplished with minimal boilerplate.
My research indicates that Observables might be what I need, but I've been unable to find clear answers on several points.
Is there an implementation of Observable in Dart that works well with Angular2?
Is an Observable meaningfully different from a Dart Stream? In particular does an Observable support getting the current value in addition to being notified about future updates?
Last but not least, assuming Observable meets my requirements, what would be the minimal syntax for declaring an Observable String property of a component, initializing it with an Observable retrieved from an injected service, displaying its value in the component's template (starting with a pre-existing value), and having updates to its value automatically mark the component for on push change detection?
If Observable does not work for this, how else should I do it? My current idea is using a custom Stream
subclass that inserts the most recent value ahead of anything else a new listener receives, and sending that through the async
pipe to handle extracting values from the stream and marking for change detection.
My ideal solution would look something like this in use:
@Injectable()
class MyService {
@observable int health;
}
@Component(
...)
class MyComponent {
@observable int health;
MyComponent(MyService service) : health = service.health;
}
And in the template:
<span>{{health | async}}</span>
Or for truly ideal, though this would have to hook into Angular's template compilation somehow (maybe with a transformer? I haven't learned how those work yet):
<span>{{health}}</span>
And with just that, it would just work.
The custom solution I now have working isn't quite as convenient as that, but it's close.