Join egghead, unlock knowledge.

Want more egghead? It's 45% off for a limited time only!

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock All Content for 45% Off

Already subscribed? Sign In

Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Handle Click Events with Subjects

    John LindquistJohn Lindquist

    While Angular usually uses event handlers to manage events and RxJS typically uses Observable.fromEvent, a good practice when using Angular and RxJS combined is to use Subjects and push the value through each event so that you can use it as part of your stream.

    angularAngular
    2 - 6
    ngrx-store@ngrx/store
    rxjsRxJS
    5 - 6
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    00:00 To add a button to control our clock, I'll go ahead and create a button. I'll just say, "update." Typically, what you do in Angular 2 is say, "click" and then just give that a handler on click. Here, you'd create that on click handler.

    00:15 Or from the other side, typically, what you do in our XJS is you'd say, "observable from event." Find the element, and then pass in the event name you want to listen to.

    00:30 We have these two different conflicting approaches where we want to find an event, or we want to handle a click here. The way we're going to solve this for now is I'm going to delete this event handler. I'm going to delete this from event.

    00:42 What I'm going to do is create something called a subject, which I'll call "click." This will be a new subject. I need to import subject. What this subject will allow me to do is call next every time I click.

    00:59 What next is going to do is push the stream forward one tick. If I take out all of this clock stuff, which was just going every second before. Now I say this.clock is this.click.

    01:13 I'm going to map those clicks to a new date. Hit save. I refresh over here. I'll click update. You can see we get our clock frozen in time at 44 seconds. I'll click update again. You can see that six seconds have passed.

    Discuss

    Discuss