我有一個可觀察的:
this.data$ = this.dataService.toGetAllData();
如果我訂閱了這個 Observable,它將回傳這個物件陣列:
this.dataService.toGetAllData().subscribe(response => console.log(response));
{
id: "1"
name: "test"
systemId: "61a92ad360863a5a0346eca1"
},
{
id: "2"
name: "test"
systemId: "61a92ad360863a5a0346eca1"
},
所以,我需要結合另一個對另一個服務的呼叫,根據 ID 回傳系統的名稱。
this.system$ = this.systemService.getSystemById(id);
如何將這兩個 observable 組合到我的變數資料中并回傳如下內容:
{
id: "1",
name: "test",
systemId: "61a92ad360863a5a0346eca1",
systemName:" System Test"
}
uj5u.com熱心網友回復:
使用switchMap:
import { switchMap } from "rxjs/operators";
this.system$ = this.dataService.toGetAllData().pipe(
switchMap(data => this.systemService.getSystemById(data.id))
);
// then this.system$.subscribe(...) or whatever you need
uj5u.com熱心網友回復:
systemdata : any
this.dataService.toGetAllData().subscribe(response => {
this.systemdata = response;
);
}
this.system = this.systemService.getSystemById(systemdata.id)
.subscribe(result => {
// here you will have a result with system name
}
ngDestroy(){
//Since You are storing the subscribe value
this.system.unsubscibe()
}
uj5u.com熱心網友回復:
當您更新問題時,您需要使用mergeMap而不是 switchMap
編輯:根據下面的評論,我更新了這段代碼。您可以更改 HTTP 獲取呼叫和回傳型別。我any僅用作示例。
`
this._httpClient.get<any[]>(<YOUR_URL>).pipe(
mergeMap((d: any[]) => {
const id = d[0].systemId;
return this._httpClient.get(<YOUR_URL>).pipe(
map((res: any) => d.map(final => {
return {
id: final.id,
name: final.name,
systemId: final.name,
systemName: res.systemName
}
}))
)
})
).subscribe((out) => console.log(out) );
`
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/375449.html
標籤:有角的
