2
\$\begingroup\$

I'm using RxJs for type along search, I setup an observable to emit a value after 1 second so it behaves like http with delay. I subscribe to it via the async operator in the template, the component has a switchMap to watch the searchTerm observable. Is this how typealong search should be implemented with RxJS?

I've included commented code of how I'd use http, is that how the http observable should be used?

Search Service:

searchTerm(term: string): Observable<Array<ObjectDefinition>> {

   /*
   return this.http.get('http://localhost:8080/api/search?term=abc')
          .pipe(
            map(result => {
              console.log(result);
              return result['body'];
            })
          );
   */

   let observer = new Observable<Array<ObjectDefinition>>((subscription) =>    {

      const timer$ = timer(1000);

      timer$.subscribe(() => {
         console.log('timer 1 second');
         subscription.next(this.objectDefinitions);
      });

   });

   return observer;

}

Testing data:

objectDefinitions = [
    new ObjectDefinition({ name: 'Sydney', description: 'Largest city in Australia'}),
    new ObjectDefinition({ name: 'Melbourne', description: 'City in south of Australia in VIC'}),
    new ObjectDefinition({ name: 'Brisbane', description: 'East coast'}),
    new ObjectDefinition({ name: 'Perth', description: 'West coast'}),
    new ObjectDefinition({ name: 'Adelaide', description: 'Small city in south Australian region'})
  ];

Component consumer:

searchInput = new FormControl();

constructor(private definitionService: DefinitionService) {
   this.definitions = this.searchInput.valueChanges
                     .pipe(
                         tap(value => console.log('input')),
                         //startWith(''),
                         debounceTime(500),
                         distinctUntilChanged(),
                         switchMap(value => this.definitionService.searchTerm(value))
                     )
}

Template using async pipe to subscribe:

<input class="format-input-button"
        (click)="clickInput()"
        [formControl]="searchInput">

<div class="format-options">
  <div *ngFor="let definition of definitions | async" class="search-result">
    <div>{{definition.name}}</div>
    <div>{{definition.description}}</div>
  </div>
</div>
New contributor
doe is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
\$\endgroup\$

Your Answer

doe is a new contributor. Be nice, and check out our Code of Conduct.

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.