0

我的目标是通过 POST 请求将信息保存在后端服务器中。我需要在前一个请求完成时一一执行这些请求。但我需要在请求之间添加一些逻辑。这些请求是使用RxJs Observables 发出的。

我会给你一些背景信息。我的应用有 5 个模型:国家、州、城市、地址、个人。

一个人有一个地址,它属于一个城市,属于一个州,属于一个国家。

每个模型都包含其“父”ID 作为外键(例如,City 具有属性“state_id”)。

所有信息都可以通过表格获得。因此,当我提交表单时,我想将此信息保存在我的后端服务器中。

为了做到这一点,我需要检查(通过 GET 请求)国家/州/城市/地址是否已经存在于数据库中,如果存在,我需要将其 ID 绑定到“孩子”,否则我需要 POST然后将其 ID 绑定到“孩子”。

我怎样才能做到这一点?我做了一些研究,并试图做这个管道concatMap()操作员。但我的问题是:我怎么能concat收到这些请求?

这是我到目前为止所拥有的:

this.countrySvc.getCountryByName(countryAux.name).pipe(
            concatMap(country1 => {
               if (country1[0] != null){
                    /*Country exists in DB*/
                    countryAux.id = country1[0].id;
                    return of(country1[0]);
                }
                else{
                    /*Country is not in DB, i need to save it before continuing*/
                    this.countrySvc.postCountry(countryAux).pipe(
                        concatMap(country2 => {
                            countryAux.id = country2.id;
                            return of(country2);
                        })
                    )
                    .subscribe();
                    return of(countryAux);
                }
            }),
            concatMap(country3 => {
                console.log("Checking what do I get here: " + country3.name + " " + country3.id);
                return country3;
        })
        )
        .subscribe();

我不知道如何正确地做到这一点。我正在寻找的请求序列是:

GET country                     // Search by name
if it exists
    state.country_id = ID       /*ID comes in response*/
else
    POST country                /*ID comes in response*/
    state.country_id = ID

/*Once this (or these) previous request(s) complete*/
/*---------So far i have implemented up to here---------*/

GET province                    
if it exists
    city.state_id = ID
else
    POST state
    city.state_id = ID

/*Once this (or these) previous request(s) complete*/   

GET city                    
if it exists
    address.city_id = ID
else
    POST city
    address.city_id = ID

/*Once this (or these) previous request(s) complete*/   

GET address
if it exists
    person.address_id = ID
else
    POST address
    person.address_id = ID

/*Once this (or these) previous request(s) complete*/   

POST person 

我怎么能做到这一点?请注意,我的主要问题是有时我需要在一些 GET 请求之间执行一些 POST 请求,而有时我不会。但是,我需要在每种情况下将一些 Observable(带有 Country/State/City... 数据)返回给下一个操作员。

4

0 回答 0