1

I am trying to get my head around Observables in RxJs. I have a page with Search box and when user start typing then Webservice returns 20 results and then when i press Show More then next 20 results are displayed and so on.

I am able to get first 20 results successfully but next 20, i am not able to merge with earlier ones.

Service

@Injectable()
export class AppService {

constructor(private http : Http) {}

search(terms : Observable < string >) {

    return terms
      .debounceTime(400)
      .distinctUntilChanged()
      .switchMap(term => this.searchEntries(term));

  }

searchEntries(term) {

    const API = "https://jsonplaceholder.typicode.com/posts/";

    return this
      .http
      .get(API)
      .map(res => res.json());
  }

}

Component

export class AppComponent {

resp : Object;
searchTerm = new Subject < string > ();

constructor(private _searchService : AppService) {
this
  ._searchService
  .search(this.searchTerm)
  .subscribe(results => {
    this.resp = results;
  });
 }
}

HTML

<span *ngFor="let res of resp | slice:0:10">
      <a href="#" class="lex-column align-items-start">
        <div class="d-flex w-100 justify-content-between">
          <h5 class="mb-1">{{res.title}}</h5>
          <small># {{res.id}}</small>
        </div>
        <p class="mb-1">{{res.body}}</p>
        <small >Donec id elit non mi porta.</small>
      </a>
 </span>

I have replaced API URL to general one

Please help in combining next 20 results to previously shown results.

Gags
  • 3,759
  • 8
  • 49
  • 96
  • Is `resp` an Array? How do you display it? Have you checked http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically? – eko Apr 02 '17 at 18:08
  • it is there... internet was down for a min.. – Gags Apr 02 '17 at 18:11
  • Instead of assigning the value how about pushing it to the array? Like: `this.resp.push(results);` Of course you need to initialize `resp = [];` – eko Apr 02 '17 at 18:11
  • an example can work.. or a small demo – Gags Apr 02 '17 at 18:11
  • If you provide a plunker, I can update it with an example – eko Apr 02 '17 at 18:16
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/139702/discussion-between-gags-and-echonax). – Gags Apr 02 '17 at 18:25

1 Answers1

0

You can use take(n) operator

return terms
      .debounceTime(400)
      .distinctUntilChanged()
      .take(10)
      .switchMap(term => this.searchEntries(term));

By this everytime only 10 items are taken.

Aravind
  • 40,391
  • 16
  • 91
  • 110
  • what this take(10) will help in achieving.. will it help in merging 10 results? – Gags Apr 02 '17 at 18:20
  • I think it will help. but try else you can make array push when you subscribe. what do you get when you tried this? and errors? – Aravind Apr 02 '17 at 18:23