When it was published, I noticed a few queries about whether something similar could be done with Angular’s
Input properties — so that they, too, could be treated as observables.
I was thinking about this last night and I’ve published a small package that can be used to observe the properties and methods of an arbitrary object:
How does it work?
Let’s look at an example:
When an object
instance is passed to the
observe function, it returns an
observables object — containing an observable source for the
name property — and a
name property of the
proxy is assigned, the observable source emits the assigned value — which is written to the console.
The TypeScript declaration for
observe ensures that the
observables object is strongly-typed — containing appropriately-typed observables for each property and method on the
Proxy is created for the instance. The proxy is used to intercept property assignments and method calls. A proxy is used for
observables, too, so that an observable source is only created for a property or method if the source is actually used.
How could it be used with Angular?
With Angular’s component API, you create a component class and Angular sets its properties and calls its methods. You could use
rxjs-observe to convert this to an observable API.
Let’s look at an example component:
In the component,
observables will contain observable sources for:
- calls to the
- calls to the
- assignments to the
Using those observables, the component: composes another observable that debounces changes to the
name input; writes said changes to the console; and unsubscribes when the component is destroyed.
name to the console isn’t particularly useful, but it does show how an observable API could be used within an Angular component.
Should it be used with Angular?
rxjs-observe was fun to write, but is it something you should really be using in an Angular component?
I dunno; it’s definitely unconventional. And it requires TypeScript 2.8 or later.
So maybe. Or maybe not, but … YOLO.
This post is also published on my personal blog: ncjamieson.com.