【问题标题】:how convert response object property from array in to request rxjs如何将响应对象属性从数组转换为请求 rxjs
【发布时间】:2022-01-10 10:33:11
【问题描述】:

API 返回一个 JSON 对象数组。

[
{
    "vacancy": "61a6597b0dc105d6e79a1f30",
    "createdBy": "61aa11644afa183fa28b0792",
    "executor": "61aa20ee25ef06b69920a505",
    "reviewer": "61aa11644afa183fa28b0792",
    "status": "Invited",
    "_id": "61aa213aeaf2af804aa1e591",
    "createdAt": "2021-12-03T13:52:58.772Z",
    "updatedAt": "2021-12-03T13:52:58.772Z"
},
...
]

而且我需要通过发出带有值的 get 请求将一些属性转换为对象。 类似的东西:

this.http.get<Application>(
      `${environment.API_ENDPOINT}/applications/assigned?status=completed`
    ).pipe(
        map(aplication => 
{
...aplication,
vacancy:this.http.get(`${environment.API_ENDPOINT}/vacancys/`+ aplication.vacancy),
executor:this.http.get(`${environment.API_ENDPOINT}/candidates/`+ aplication.executor)
}
    )

【问题讨论】:

标签: typescript rxjs


【解决方案1】:

您需要使用“Higher Order Mapping Operator”,它将在内部订阅一个可观察对象并发出它的发射。

在您的情况下,switchMap 将适用于此。由于您需要进行两次不同的调用,我们可以使用 forkJoin 创建一个 observable,在收到两个结果时发出两个结果:

myObj$ = this.http.get<Application>('/applications/assigned').pipe(
    switchMap(aplication => forkJoin({
        vacancy  : this.http.get(`environment.API_ENDPOINT}/vacancys/${vacancy}`),
        executor : this.http.get(`environment.API_ENDPOINT}/candidates/${executor}`)
    }).pipe(
        map(({vacancy, executor}) => ({...aplication, vacancy, executor})
    ))
);

【讨论】:

    猜你喜欢
    • 2019-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    • 1970-01-01
    • 2017-10-15
    • 2022-12-08
    相关资源
    最近更新 更多