angularrxjsobservableangular2-observablessubject-observer

Making Subscribe to wait in Angular 4 for Subject


I have a text field in my HTML which calls back-end service in real time based on text entered. If a user enters something like 'abc', my service returns an object array which has this 'abc' name.

I am using Observable and Subject for this and I am returning processed service in my component. Please see the code.

HTML Code

<input size="30" type="text" (keyup)="searchTerm$.next($event.target.value)">

Component Code

import { Subject } from 'rxjs/Subject';

searchString$ = new Subject<string>();

constructor() {

    this.searchString$.debounceTime(500)
    .distinctUntilChanged()
      .map(searchText => {
        return this.backEndService.fetchSearchStringData(searchText);
      })
      .subscribe(result => {
        console.log('result');
        console.log(JSON.stringify(result));

      });
}

When I I type 'abc' then it calls this fetchSearchStringData method. The service call is nothing but simple restService.post call and then setting the object is observable. Using that data to filter something and returning the finalized array.

But my component .subscribe us getting called first and only one time and it shows undefined value. (Where I am consoled.logging 'result').

How do I make sure I get the data once it gets a return from service in my subscribe of the component?

Thanks in advance.


Solution

  • I cannot be sure unless you post code on how you make the fetchSearchStringData call. But inside you need to return a Promise or Observable. It looks like you're not returning anything, thus consolte.log prints undefined.

    Then you can use switchMap to unwrap the result into the stream.

    this.searchString$.debounceTime(500)
      .distinctUntilChanged()
      .switchMap(searchText => {
        return this.backEndService.fetchSearchStringData(searchText);
      })
      .subscribe(result => {
        console.log('result');
        console.log(JSON.stringify(result));
      });