Join egghead, unlock knowledge.

Want more egghead?

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

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Build fully reactive APIs in Angular 2 with Observables

    Christoph BurgdorfChristoph Burgdorf

    In this video you'll learn how Observables can improve the overall API design by designing APIs that accept Observables as arguments



    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




    Now that we've built an instant search that deals with all this tricky stuff, wouldn't it be actually better if we had a smarter Wikipedia search service that would handle all these details behinds the scenes?

    As a component outdoor, I shouldn't have to worry about debalancing, deduplicating, and dealing with out of order responses. Because observables are first class objects, we can put APIs that not only return observables, but also accept observables as arguments. Let's make our Wikipedia search service smarter.

    We'll keep the search method, but rename it raw search. We'll build a smarter one on top of it. We call the smarter one simply search, and it accepts two arguments. We name the first one terms, but instead of being a simple string, it's an observable of string. The second one we call debalance MS, and it gets a default value of 100.

    We'll use that to configure the debalancing but allow the caller to override the default value. We also have to write another import to pull in the observable type. We import that one from axjs/observable.

    Inside our new search method, we just paste all the observable apparatus that we previously used from inside out component to apply them on top of the terms observable that we get past as an argument. I switched my panhandler to invoke the URL search method, and remove the subscribe part.

    Now we jump back to our component, and here we can use our smarter search service. We invoked this search method which now expects us to pass an observable of string as its first parameter, and we have that. It's this dot term which is the raw, unprocessed observable from our text box.

    Then we subscribe to the observable, and we get access to the results which are on area of strings just as before. We exposed them on the items property of our component, and then we remove all the rest of the code that the component doesn't have to care about anymore.

    Once the browser's ready, let's see if it still works. I can type. It's still debalancing. It handles out of order responses, and it's all nicely hidden behind a service.