如何在用户输入按键事件上调用多个请求?

时间:2019-06-25 21:32:24

标签: angular rxjs

我正在尝试在文本框输入键向上事件中调用2个http请求。

message

这是单个请求可以正常工作的地方:

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);
}

2 个答案:

答案 0 :(得分:1)

对于每个输入信号切换映射到两个组合请求:

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;
  });
}

答案 1 :(得分:1)

像这样更新您的代码:

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);
    }