How to make POST requests to save a list of objects in the hierarchical structure in angular

徘徊边缘 提交于 2019-12-24 22:49:58

问题


I have a list of objects in the hierarchical structure which are related by parentId, for example:

[
  {
    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: []  
      }
    ]
]

I need to save objects one by one through web service by calling POST method six times. The requirement is that I have to save them sequentially. I mean, I have to wait until Parent Unit is saved, when the web service returns new id of the parent object and then I can make another POST request to web service with modified parentId for Unit Child objects.

I use Observables for making web services in my angular app. Any ideas how can I do it?


回答1:


You can use switchMap

Here's a basic example of how it works

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

Basically, you get the first id, switchmap it to use it on the 2nd call etc...

Read more about it here: https://www.learnrxjs.io/operators/transformation/switchmap.html



来源:https://stackoverflow.com/questions/49450617/how-to-make-post-requests-to-save-a-list-of-objects-in-the-hierarchical-structur

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!