【问题标题】:Angular 4 / RxJS, send HTTP of an array in sequenceAngular 4 / RxJS,按顺序发送数组的HTTP
【发布时间】:2017-09-29 07:16:09
【问题描述】:

尝试按顺序一个接一个地 http 发布数组中的项目。知道应该使用 RxJS flatMap 但无法使其工作。基本上我需要这样的东西:

item 是一个名为 items 的数组的元素,想要遍历数组并发送每个 item。

    this.http.post(url, item)
        .subscribe(
          (response) => {
            // call the same http.post again to send the next item
          },
          (error) => {
            this.app.error(error.json() as Error); // exit
          }         
        )

感谢您的帮助。

【问题讨论】:

    标签: angular rxjs flatmap


    【解决方案1】:

    也许可以试试concat

    Rx.Observable.concat(...items.map(item => this.http.post(url, item)).subscribe(res => doSmthWithResponse());
    

    【讨论】:

    • 感谢您的回复。 “ng build”抱怨“'Observable[]' 类型上不存在属性 'subscribe'。”在以下代码上: Observable.concat(items.map( (item:Item) => this.http.post(url, item)) .subscribe(response => this.doSomething() ) );
    • 您忘记在 items.map 前添加“...”(扩展运算符)。试试 Observable.concat(...items.map( (item:Item) => this.http.post(url, item)) .subscribe(response => this.doSomething() ) );
    • 真的不知道传播算子,谢谢。但是这段代码得到了完全相同的错误: Observable.concat(...items.map( (item:Item) => this.http.post(url, item)).subscribe(response => this.doSomething() ));如果问题出在我的导入中: import {Observable} from 'rxjs/Observable';导入'rxjs/add/operator/map';导入'rxjs/add/observable/concat';还有其他进口吗?非常感谢。
    • 你在订阅前错过了一个右括号,试试这个:Observable.concat(...items.map( (item:Item) => this.http.post(url, item)))。订阅(响应 => this.doSomething() ) );
    【解决方案2】:
      this.http.post(url, item).map(res => res.json())
                switchMap(this.http.post(url1, item).map(res => res.json()))    
    

    【讨论】:

      【解决方案3】:

      您可以尝试使用 from 和 flatmap

      Observable.from(items)
          .flatMap(item => this.http.post(url, item))
          .subscribe({
              res => console.log("your response"),
              error => console.log("your error"),
              () => doSomethingAtEnd()
          });
      

      【讨论】:

        猜你喜欢
        • 2020-03-26
        • 2018-04-19
        • 1970-01-01
        • 1970-01-01
        • 2015-05-09
        • 2018-05-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多