This Lesson is for Members

Subscribe today and get access to all lessons! Plus direct HD download for offline use, enhances transcripts, member comment forums, and iTunes "podcast" RSS feed. Level up your skills now!

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Debounce the user input in Angular 2 using debounceTime

    Christoph BurgdorfChristoph Burgdorf

    In this video we'll learn how to use the debounceTime operator to tame the user input for an instant search.

    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 Now that we consumed the input event of our text box as an observable, we can apply a whole set of AX operators on top of it to create a more meaningful observable for our specific use case.

    00:10 When we look at the network type of our browser, we will notice that we currently make requests to the Wikipedia API with every single keystroke. In a real-world scenario, we wouldn't like to hammer our server like this, and rather be more economical with our resources.

    00:25 What we actually want is to make requests whenever the user stopped typing for a brief moment. In technical terms, that means skip all the notifications up to the point where there hasn't been a new notification for at least say, 400 milliseconds. Once we have that gap, that the last notification comes through.

    00:44 The good news is there's AX operator for exactly that behavior, and it's called debounceTime. Let's turn back to our code and first import the operator. We do that right off of the import that we did for the map operator.

    00:56 Since they are all shared across the application, we can leave them right here. What we do is we apply the debounceTime operator on top of our term observable. This doesn't directly modify the term observable. Instead, it creates a completely new observable that has the desired behavior.

    01:13 Let's check out the network type of our browser again, and see the difference. We can clearly see that we don't perform request on every keystroke anymore. The requests go out as soon I rest my fingers for a brief moment, which is exactly what we want.

    Discuss

    Discuss