Whistler
Whistler

Reputation: 1977

How can I call multiple requests on user input key up event?

I'm trying to call 2 http requests on textbox input key up event.

ngAfterViewInit() {
fromEvent(this.input.nativeElement, 'keyup')
return forkJoin(
  this.playerService
  .findPlayers(1, 'userName', this.input.nativeElement.value, 'asc', 0, 20),
  this.messagesService.getConversations()
)
.pipe(
  map(([first, second]) => {
    return { first, second };
  })
)
.subscribe({first, second} => this.players = first.players, this.conversations = second);
}

This is what works correctly with single request:

ngAfterViewInit() {
fromEvent(this.input.nativeElement, 'keyup')
.pipe(
  startWith({}),
  switchMap(() => {
    return this.playerService
    .findPlayers(1, 'userName', this.input.nativeElement.value, 'asc', 0, 20)
    .map(data => {
      return data.players;
    });
})).subscribe(players => this.players = players);
}

Upvotes: 1

Views: 118

Answers (2)

Xesenix
Xesenix

Reputation: 2548

For every input signal switch map to two combined request:

ngAfterViewInit() {
  fromEvent(this.input.nativeElement, 'keyup').pipe(
    switchMap(() => forkJoin(
      this.playerService.findPlayers(1, 'userName', this.input.nativeElement.value, 'asc', 0, 20),
      this.messagesService.getConversations()
    )),
    map(([first, second]) => ({ first, second }))
  ).subscribe(({first, second}) => {
    this.players = first.players;
    this.conversations = second;
  });
}

Upvotes: 1

user2216584
user2216584

Reputation: 5602

Update your code like this:

ngAfterViewInit() {
    fromEvent(this.input.nativeElement, 'keyup')    
    .pipe(
      switchMap(() => forkJoin(this.playerService.findPlayers(1, 'userName', this.input.nativeElement.value, 'asc', 0, 20),
                                this.messagesService.getConversations())
      map(([first, second]) => {
        return { first, second };
      })
    )
    .subscribe({first, second} => this.players = first.players, this.conversations = second);
    }

Upvotes: 1

Related Questions