【发布时间】:2020-07-26 19:10:25
【问题描述】:
我有两个接口,分别是Team和Company
public interface Team {
id: number;
name: string;
companyId: number;
}
public interface Company {
id: number;
name: string;
}
这是示例数据:
"companies": [
{
"id": 3,
"name": "XSoftware",
"location": "Nagar"
},
{
"id": 5,
"name": "Google",
"location": "Seattle"
},
{
"id": 7,
"name": "YS",
"location": "Dhanmondi"
},
{
"id": 8,
"name": "Amazon",
"location": "Seattle DC"
},
{
"name": "ToTD",
"location": "Pink City",
"id": 10
}
]
"teams": [
{
"id": 1,
"name": "Team X",
"expertise": "Java",
"companyId": 3
},
{
"id": 2,
"name": "Team Y",
"expertise": "Angular",
"companyId": 3
},
{
"id": 3,
"name": "Team Z",
"expertise": "Spring Boot",
"companyId": 8
},
{
"id": 4,
"name": "Team M",
"expertise": "Node Js",
"companyId": 5
}
]
所以我想根据 companyId 将 company 作为属性分配给每个团队。 像这样:
"teams": [
{
"id": 1,
"name": "Team X",
"expertise": "Java",
"companyId": 3,
"company": {
"id": 3,
"name": "XSoftware",
"location": "Nagar"
}
},
{
"id": 2,
"name": "Team Y",
"expertise": "Angular",
"companyId": 3,
"company": {
"id": 3,
"name": "XSoftware",
"location": "Nagar"
}
},
{
"id": 3,
"name": "Team Z",
"expertise": "Spring Boot",
"companyId": 8,
"company": {
"id": 8,
"name": "Amazon",
"location": "Seattle DC"
}
},
{
"id": 4,
"name": "Team M",
"expertise": "Node Js",
"companyId": 5,
"company": {
"id": 5,
"name": "Google",
"location": "Seattle"
}
}
]
那么我如何使用 RxJs 来实现这一点。 我有两个 observable 分别返回 Team[] 和 Company[] 的 Observable。
const teams$: Observable<Team[]> = this.httpClient.get<Team[]>('/teams');
const companies$: Observable<Company[]> = this.httpClient.get<Company[]>('/companies');
那么,如何做到这一点?我知道它可以以命令式的方式完成(通过使用循环、if-else 等),但我想通过只使用反应式运算符、观察者来以反应式的方式做到这一点。
【问题讨论】:
-
我认为“rxjs 方式”这样做没有意义,因为您将响应作为每个请求发出的数组,而不是作为流。我只需对两个 observable 做一个
forkJoin,然后做所有必要的事情(或者我会以更实用的方式来做)
标签: arrays angular reactive-programming rxjs6 rxjs-observables