我有两个界面,分别是团队和公司
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实现这一目标。我有两个可观察值,分别返回Team []和Company []的Observable。
const teams$: Observable<Team[]> = this.httpClient.get<Team[]>('/teams');
const companies$: Observable<Company[]> = this.httpClient.get<Company[]>('/companies');
所以,该怎么做?我知道可以通过命令式方式(通过使用循环,if-else等)来完成此操作,但是我想仅通过使用反应式运算符,观察者以反应式方式进行此操作。
正如@ShanPooShan所说,一种方法是使用forkJoin
运算符。看看下面的代码片段
const teams$ = this.httpClient.get<Team[]>('/teams');
const companies$ = this.httpClient.get<Company[]>('/companies');
const teamsWithCompanies = forkJoin(teams$, companies$).pipe(
switchMap((values: any[]) => {
const teamsWithCompaniesResponse: TeamWithCompany[] = [];
const teamArray = values[0];
teamArray.forEach((team) => {
const teamWithCompany: TeamWithCompany = {
id: team.id,
name: team.name,
expertise: team.expertise,
companyId: team.companyId,
company: values[1].find(c => c.id === team.companyId)
}
teamsWithCompaniesResponse.push(teamWithCompany);
})
return of(teamsWithCompaniesResponse);
})
).subscribe(response => {
console.log('[RESPONSE]', response);
})