angulartypescriptmapquest

two search variables in api pipe typescript


I'm sure I'm doing something stupid here, but I can't get figure out how to pass 2 variables using the approach that I'm using, which utilizes some rxjs. I have 2 search variables for a navigation app, from and to, which are entered into boxes searchFrom and searchTo in my html, but I can't figure out how to work it. either searchTerms needs to be an array somehow or ... something.

export class AppComponent implements OnInit {
  mapResult: any;
  to: any;
  from: any;

  private searchFrom: Subject<string>;
  private searchTo: Subject<string>;

  constructor(private mapQuestService: MapQuestService) {  }

  search(to: string): void {
    this.searchTo.next(to); }

  search(from: string): void {
      this.searchFrom.next(from); }



  ngOnInit() {

this.from = 'boston';
this.to = 'poughkeepsie';

this.searchTerms = new Subject<string>();
this.searchTerms.pipe(

    debounceTime(1000),

    distinctUntilChanged(),
    switchMap((to, from) => {
      return this.mapQuestService.getMap(this.to, this.from);

  ))
  .subscribe((result: any) => {

    this.mapResult = result.items;
  });
}

}

any ideas?


Solution

  • Try using combineLatest instead of another subject:

    this.searchTerms = combineLatest(this.to, this.from);
    this.searchTerms.pipe(
      debounceTime(1000),
      distinctUntilChanged(),
      switchMap((to, from) => this.mapQuestService.getMap(to, from))
    )
    .subscribe((result: any) => this.mapResult = result.items);
    

    Stackblitz Demo two observables