RxJS: My Learning is Observable — Part 1

Mike Brocchi
1 min readMay 12, 2016

--

Today I made a commitment to myself, to learn and use RxJS.

I have been contributing to the Angular CLI rather aggressively for the past 6 months and decided it is time to focus on improving the Angular applications that I am writing as well. The best place to start, observables.

So where to begin? I have a little experience using observables but only enough to make one thing work (exposing an event from one angular component to another). I got that to work by just subscribing to the observable.

this.http
.get('http://fake-url')
.map(res => res.json())
.subscribe((data) => { this.httpData = data; });
<ul>
<li *ngFor="let item in httpData">
{{item}}
</li>
</ul>

And based upon the documentation there is something called the AsyncPipe which will handle that subscription for me, which means that I don’t need to keep local state inside my component, WIN! But how do I go about using this in my code.

Turns out it is rather easy, by simply setting httpData property of the component to the observable which is returned by http.get and allowing the angular async pipe subscribe to the observable the component is no longer responsible for managing the subscription. Voila:

this.httpData = this.http
.get('http://fake-url')
.map(res => res.json());
<ul>
<li *ngFor="let item in httpData | async">
{{item}}
</li>
</ul>

This is only a small sample of what can be done with observables, but it is best to start small and grow rather than be intimidated by looking at the entire landscape.

Next up: learning operators

--

--