This lesson is for PRO members.

Unlock this lesson NOW!
Already subscribed? sign in

Prevent unnecessary requests in Angular 2 with distinctUntilChanged

1:15 Angular 2 lesson by

In this video you'll learn how to use the distinctUntilChanged operator to prevent making unnecessary requests.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

In this video you'll learn how to use the distinctUntilChanged operator to prevent making unnecessary requests.

Avatar
Roydell

You're going too fast without explaining.

In reply to egghead.io

Now that we debounced the user input, we are saving our API from tons of unnecessary traffic, but there's still room for improvement, and rx makes things really easy.

When I type ANG and then rest my fingers, we see the request going out.

Request going out

Now, let's see what happens when I hit backspace to cut the G, and then put it right back in. What happens is that we make two subsequent requests to fetch items for the term ANG.

Since we're already displaying the search results for exactly that character sequence, we could actually save the request. Thinking in terms of observable streams, what we need is an operator to filter out subsequent duplicate notifications.

Let's import the distinctUntilChanged operator, which does exactly that.

app.component.ts

import 'rxjs/add/operator/distinctUntilChanged';

We can think of it as a filter operator that works over a buffer of the last two notifications to remove duplicates. We add it right after debounceTime operator.

app.component.ts

export class AppComponent {}
  items:Array<string>;
  term$ = new Subject<string>();
  constructor(private service:WikipediaSearchService) {
    this.term$
        .debounceTime(400)
        .distinctUntilChanged()      
        .subscribe(term => this.search(term))
  }

  search(term: string) {
    this.service.search(term)
                .subscribe(results => this.items = results);
}

Let's turn to our browser again and do exactly what we did before. We type ANG, and we see the request goes out. Now, I hit backspace, remove the G, and put it right back in, and I do that a couple of times. We notice that it's not making any new requests. It's still making new requests as soon as the term changes, which is exactly what we want.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?