【问题标题】:Angular HTTP Post multiple JSON objectsAngular HTTP Post 多个 JSON 对象
【发布时间】:2020-02-18 10:01:57
【问题描述】:

我正在尝试通过 HTTPClient 发布多个 JSON 对象。不过,我想一次将它们作为一个对象发送,一个接一个地连续发送。我该怎么做?

我目前正在通过另一个对象数组进行映射,我已经必须创建一个要发布的新对象数组。我可以使用for循环一一成功地console.log巨型对象数组(86个对象);但我不知道如何一一发布它们。

    this.newdailys = this.rooms.map(room => ({ 
      id: null,
      timeCreated0: this.date,
      roomid1: room.id,
      guestwaiting2: null,
      supervisorconfirmed3: null,
      finishedcleaning4: null,
      staffid5: null,
      bathtowelIN6: null,
      bathtowelOUT7: null,
      bathmattIN8: null,
      bathmattOUT9: null,
      sheetSIN10: null,
      sheetSOUT11: null,
      duvetSIN12: null,
      duvetSOUT13: null,
      sheetDIN14: null,
      sheetDOUT15: null,
      duvetDIN16: null,    
      duvetDOUT17: null,
      pillowcaseIN18: null,
      pillowcaseOUT19: null,
      bolstercaseIN20: null,
      bolstercaseOUT21: null,
      sugarIN22: null,
      teaIN23: null,
      coffeeIN24: null,
      creamerIN25: null,
      stirerIN26: null,
      mwaterIN27: null,
      slipperIN28: null,   
      barsoapIN29: null,
      shampooIN30: null,
      dentalkitIN31:null,
      cottonbudIN32: null,
      showercapIN33: null,
      roomtissueIN34: null,
      HBTIN35: null,
      coasterglassIN36: null,
      plastikbeningIN37: null,
      mug238: null,
      electricjug39:null,
      tumblerglass240:null,
      traymerah141: null,
      sugarbowl142: null,
      bedskirting43: null,
      bedpad44: null,
      hanger45:null,
      telpon46: null,
      lamp47: null,
      hairdryer48: null,
      jetshower49: null,
      television50: null,
      underbed51: null,
      timeCompleted52: null,
      deleted53: false,
      }))
      for (let i = 0; i < newdailys.length; i++) {
      return this.http.post(http://localhost:3000/dailys, newdailys[i])}} 

/// what has worked was for (let i = 0; i < newdailys.length; i++) {
      console.log(newdailys[i])}


【问题讨论】:

  • “我该怎么做?” — 完全取决于服务器端进程如何(以及如果)期望多个对象被格式化。

标签: angular for-loop post rxjs httpclient


【解决方案1】:

这个:

for (let i = 0; i < newdailys.length; i++) {
      return this.http.post(http://localhost:3000/dailys, newdailys[i])
}

在发布第一个对象后总是会返回。您的 return 语句将立即返回到函数调用者并中止 for 循环。

就像 Quentin 在他的评论中已经提到的那样,这完全取决于您的服务器端期望它们如何格式化。但根据您的问题,我假设您只想在单独的发布请求中发送每个对象。

只需删除 for 循环中的 return 语句。当然,您想对请求的响应做一些事情。一种解决方案可能是使用 rxjs forkJoin operator. 并返回结果 observable。

例如,你可以想出类似的东西:

postObjects(newdailys: any[]) {
    const postObservables: Observable<any>[] = newdailys.map(daily => this.http.post('http://localhost:3000/dailys', daily));
    return forkJoin(...postObservables);
  }

但是就像上面提到的,这完全取决于你想对结果做什么。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多