我有一個看起來像的模型:
export class Info {
Id: number;
Participant: object;
}
我有一個獲取Info物件串列的端點,但它不獲取Participant屬性。我需要從不同的服務中獲取這些物件,但是我無法理解如何使用多個 Observable 以及一個依賴于先前回傳值的 Observable。
我正在獲取一個陣列,Info然后通過該陣列Participant從其他服務中獲取物件。我在 observable 之外分配了我的組件的視圖部分,所以我在顯示值之前遇到了問題,直到值實際存在。
部分.html
<tr *ngFor="let connection of connections">
<td> {{connection.Id}} </td>
<td> {{connection.Participant.Name}} </td>
</tr>
組件.ts
ngOnInit() {
this.connectionInfoService.GetInfo().subscribe((connections: Info[]) => {
connections.forEach(x => {
this.participantService.getParticipantByID(x.Id).subscribe((participant) => {
x.Participant = participant;
});
});
this.connections = connections;
});
}
我進入Cannot read properties of null (reading 'Name')控制臺是因為顯然Name不是 的屬性,null直到實際上有Participant. 我怎樣才能更好地處理這個問題?我寧愿在我的ngOnInit服務獲取代碼中處理它,但我不知道如何處理依賴于另一個 Observable 的 Observable。
uj5u.com熱心網友回復:
你永遠不應該有subscribe另一個的內部subscribe。當您需要轉換從 Observable 發出的資料時,請使用 RxJs 運算子。
以下代碼未經測驗,但希望它足夠接近以使您走上正確的軌道:
import { combineLatest } from 'rxjs';
import { switchMap} from 'rxjs/operators';
// ...
ngOnInit() {
this.connectionInfoService.GetInfo().pipe(
switchMap(connections => {
// For each connection...
const connections$ = connections.map(connection => {
// Create an Observable to fetch the participant.
const participant$ = this.participantService.getParticipantByID(connection.Id);
return participant$.pipe(
// When the participant is recieved, add the participant
// to the connection and return the connection.
map(participant => {
connection.Participant = participant;
return connection;
})
);
});
// Use the RxJs combineLatest function to return an Observable that
// emits when all the connections$ Obervables have emitted.
return combineLatest(connections$);
})
).subscribe(connections => this.connections = connections);
}
旁白:我使用了向$參考 Observables 的變數添加尾隨的約定。您可以在此處閱讀有關該約定的更多資訊。
此示例中的關鍵 RxJs 運算子是switchMap運算子。使用這個運算子,每次外部 Observable 發出時,switchMap都會有效地訂閱內部 Observable。在這種情況下,外部 Observable 是this.connectionInfoService.GetInfo(),內部 Observable 是combineLatest(connections$)。
- 切換映射
- 結合最新
獎金
與其訂閱組件類中的 Observable,不如考慮使用 Angular 的異步管道:
ngOnInit() {
this.connections$ = this.connectionInfoService.GetInfo().pipe(
// same as shown above.
);
}
<tr *ngFor="let connection of connections$ | async">
<td> {{connection.Id}} </td>
<td> {{connection.Participant.Name}} </td>
</tr>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/395882.html
