[英]Angular map http response value with another http call
我有一個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
})
但是正如我所期望的那樣,它正在返回可觀察到的答案,而且我不確定如何獲得答案。 謝謝您幫忙
這應該工作。 如果您需要解釋,請提出要求!
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}`}))
)
)
您可以使用MergeMap。 例如,您可以嘗試這樣的操作-
this.service.getUserData(id).pipe(
mergeMap( (user:User) => this.service.getCommuneByCode(code).pipe(
map(commune => user.libAddress = `${commune.postalCode} - ${commune.departement}`)
)
)
).subscribe();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.