【问题标题】:How can I pass parameters through RXJS chain?如何通过 RXJS 链传递参数?
【发布时间】:2018-03-23 17:29:47
【问题描述】:

我有一个包含 3 个项目的数组:

arrActions: Array<Item> = [{ url: 'http://1.com', data: '5' }, 
                           { url: 'http://2.com', data: '6' }, 
                           { url: 'http://3.com', data: '7' }];

我想为每个项目执行一个 Ajax 请求。那没问题 。但我还需要知道我在subscribe 回调中处理的是哪个项目。

这是我尝试过的:

 from(this.arrActions).pipe(
      mergeMap((i) => this.ajaxAlike(i)))
      .subscribe(data => {
        console.log(data)
      });

这会返回:

但我不知道每个回调与哪个请求相关。

所以我想也许是这样的:

from(this.arrActions).pipe(  
      mergeMap((i) =>(of({data:i.data, url: this.ajaxAlike(i.url)}))))
      .subscribe(data => {
        console.log(data)
      });

但是现在,http 没有执行:

此外,我想我在这里走错路了。

Online demo

问题:

我如何调用所有 url,并在 subscribe,同时获得 http 结果 + item 本身?

【问题讨论】:

    标签: javascript rxjs rxjs5


    【解决方案1】:

    您可以在收到每个结果后对其进行映射:

    from(this.arrActions)
      .pipe(
        mergeMap((i) => this.ajaxAlike(i)
          .pipe(
            map(result => ({ data: i.data, result })),
          )
        )
      )
      .subscribe(data => {
        console.log(data)
      }, err => {
        console.log(' error which is ->', err);
      });
    

    这将打印以下输出:

    {data: "5", result: "httpResponse"}
    {data: "6", result: "httpResponse"}
    {data: "7", result: "httpResponse"}
    

    您更新了演示:https://stackblitz.com/edit/angular-http-client-y43j1w?file=app/app.component.ts

    【讨论】:

    • 谢谢。 :) (顺便说一句,我不想​​放 angular 标签,因为恕我直言,它与 rxjs 完全相关。不是吗?)
    • 啊哈,没问题
    猜你喜欢
    • 2015-04-04
    • 1970-01-01
    • 2018-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多