【问题标题】:How to make POST requests to save a list of objects in the hierarchical structure in angular如何发出POST请求以角度保存层次结构中的对象列表
【发布时间】:2018-03-23 13:20:07
【问题描述】:

我有一个层次结构中的对象列表,这些对象与 parentId 相关,例如:

[
  {
    id: 10,
    name: "Parent Unit 1",
    parentId: null, 
    children: 
    [
      {
        id: 11,
        name: "Unit Child 1.1",
        parentId: 10,
        children:
        [
          {
            id: 15,
            name: "Unit Child 1.1.1",
            parentId: 11,
            children: []
        ]   
      }, 
      {
        id: 12,
        name: "Unit Child 1.2",
        parentId: 10,  
        children: []
      }
    ]   
  },
  {
    id: 13,
    name: "Parent Unit 2",
    parentId: null, 
    children: 
    [
      {
        id: 14,
        name: "Unit Child 2.2",
        parentId: 13,
        children: []  
      }
    ]
]

我需要通过 Web 服务通过调用 POST 方法六次来一一保存对象。要求是我必须按顺序保存它们。我的意思是,我必须等到 Parent Unit 被保存,当 Web 服务返回父对象的新 id 时,我可以使用修改后的 parentId 向 Web 服务发出另一个 POST 请求 Unit Child 对象。

我使用 Observables 在我的 Angular 应用程序中创建 Web 服务。任何想法我该怎么做?

【问题讨论】:

  • 其实最好一次发送全部数据,然后让服务器处理。否则在处理失败的请求时您将面临复杂性。当其中一个请求失败时会发生什么?你应该再次开火吗?当数据已经存在时服务器如何响应?
  • 抱歉没有在原问题下指出来
  • 感谢您的评论!你的描述很有道理。再次感谢。

标签: angular observable sequential


【解决方案1】:

你可以使用switchMap

这是一个如何工作的基本示例

Rx.Observable.of('some_url')
  .switchMap(url => this.http.get(url))

基本上,您获得第一个 id,将其切换映射以在第二次调用时使用它等等...

在此处了解更多信息:https://www.learnrxjs.io/operators/transformation/switchmap.html

【讨论】:

    猜你喜欢
    • 2014-02-16
    • 2018-11-10
    • 2019-10-14
    • 2011-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-22
    • 1970-01-01
    相关资源
    最近更新 更多