0

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?

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

6 Comments

That's cool, although (noob question) Right now I am getting my 2 inputs from html boxes <form > <input #searchFrom id="from-box" (keyup)="search(searchFrom.value)"/> <input #searchTo id="to-box" (keyup)="search(searchTo.value)"/> </form> so question is, how do I set searchTerms in that?
@AndrewSteier what do you mean by set? if you mean get your input to call next on the subjects, I'll update my answer with that.
So the problem I'm having is, using your method or using a modified version of mine, I'm not able to successfully pass my two input boxes into the function. so you're using searchTerms, but while I currently have this.to and this.from hardcoded, they aren't getting my search box input.
@AndrewSteier I've created a live working example for you on stackblitz, please see update on post.
So... Yes, thank you for going to the trouble. What I still don't grasp, and maybe it's just a matter of explanation, is how to modify that to take 2 distinct inputs.. my getMap takes two distinct arguments from two different search boxes. If it was just the one term, I think I could pull it off.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.