[英]Angular - How to return an observable from another observable
我有一個訂閱服務的組件。 該方法繼而訂閱了其他服務中的可觀察對象。 我想將數組從最后一個服務傳遞回第一個服務,后者又將該數組傳遞回組件。 更具體地說,該組件調用其本地服務,然后調用本地服務,該數據服務使用http客戶端訪問我的數據庫。 http客戶端正在運行,數據服務將數組返回到本地服務。 本地服務接收到該數組,但是我無法弄清楚如何將該數組作為可觀察的內容傳遞回組件。 以下是簡短的代碼塊:
零件:
this.soccerService.getPlayers(0).subscribe(
teamPlayers => {
this.teamPlayers = teamPlayers;
this.currentTeam = teamPlayers.team;
this.players = teamPlayers.players;
this.teamColor = this.currentTeam.color;
}
足球服務
this.dataService.getPlayers(teamId).subscribe( players => {
this.players = players;
this.teamPlayers.team = this.team;
this.teamPlayers.players = this.players;
this.teamPlayers = {
team: this.team,
players: players
};
return of(this.teamPlayers);
});
數據服務
getPlayers(id): Observable<Player[]> {
debugger;
return this.http.get<Player[]>(apiRootCustom + '/GetPlayers/' + id, httpOptions);
}
您正在足球服務中使用subscribe
。 您想要做的是從數據服務中傳回可觀察對象,並讓您的足球服務在繼續將其傳遞回組件之前稍微擴大響應。
將subscribe
視為可觀察對象的“道路的盡頭” ,但是您可以將可觀察對象傳遞給任意數量的訂閱者,並隨時使用管道對響應執行不同的操作。
使用不同的運算符更改不同訂戶的可觀察對象的響應的示例: StackBlitz
在您的代碼中嘗試如下操作:
Compoent
this.soccerService
.getPlayers(0)
.subscribe(
(teamPlayers) => {
this.teamPlayers = teamPlayers;
this.currentTeam = teamPlayers.team;
this.players = teamPlayers.players;
this.teamColor = this.currentTeam.color;
},
(error: any) => {
// TODO: handle any errors
}
);
足球服務
this.dataService
.getPlayers(teamId)
.pipe(
map((players) => {
this.players = players;
this.teamPlayers.team = this.team;
this.teamPlayers.players = this.players;
this.teamPlayers = {
team: this.team,
players: players
};
return this.teamPlayers;
})
);
數據服務
getPlayers(id): Observable<Player[]> {
return this.http.get<Player[]>(`apiRootCustom/GetPlayers/${id}`, httpOptions);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.