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

Already subscribed? Sign In

Autoplay

    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

    angularAngular
    ^2.0.0
    rxjsRxJS
    ^5.0.0
    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'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?

    00:10 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.

    00:26 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.

    00:45 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.

    00:59 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.

    01:17 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.

    01:33 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.

    01:48 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.

    Discuss

    Discuss