我有一个看起来像这样的http呼叫:
public getCommuneByCode(code: string): Observable<Commune> {
return this.http.get<Commune[]>(ApiUrl);
}
公社模型如下:
export interface Commune {
code: string;
departement: string;
postalCode: string;
}
我还有另一个http调用来获取用户数据:
public getUserData(id: number): Observable<User> {
return this.http.get<User>(ApiUrl);
}
用户模型:
export interface User {
id: number;
name: string;
libAddress: string;
}
我想做的是使用getCommuneByCode服务的响应来设置libAddress属性,如下所示:
this.service.getUserData(id).pipe(
map((user: User) => {
user.libAddress = this.service.getCommuneByCode(code).pipe(
map(commune => `${commune.postalCode} - ${commune.departement}`)
);
return user;
})
).subscribe((userWithLibAddress) => {
// user object with all data and libAddress property is equal to ex: 99999 - DepartementXX
})
但是,正如我期望的那样,它返回的是可观察到的答案,而且我不确定如何获得答案。谢谢您的帮助
答案 0 :(得分:3)
这应该有效。如果您需要解释,请提出要求!
forkJoin(
this.service.getUserData(id),
this.service.getCommuneByCode(code)
).pipe(
map(([user, commune]) => ({ ...user, libAdress: `${commune.postalCode} - ${commune.departement}`})
);
编辑:如果您需要按顺序拨打电话:
this.service.getUserData(id).pipe(
switchMap(user => this.service.getCommuneByCode(user.code)).pipe(
map(commune => ({ ...user, libAdress: `${commune.postalCode} - ${commune.departement}`}))
)
)
答案 1 :(得分:1)
您可以使用MergeMap。例如,您可以尝试这样的事情
this.service.getUserData(id).pipe(
mergeMap( (user:User) => this.service.getCommuneByCode(code).pipe(
map(commune => user.libAddress = `${commune.postalCode} - ${commune.departement}`)
)
)
).subscribe();