我有一个订阅服务中可观察对象的组件。该方法继而订阅了其他服务中的可观察对象。我想将数组从最后一个服务传递回第一个服务,后者又将该数组传递回组件。 更具体地说,该组件调用其本地服务,然后调用本地服务,该数据服务使用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);
}
答案 0 :(得分:0)
您在足球服务中使用subscribe
。您要做的是从数据服务中传回可观察对象,并让足球服务在继续将其传递回组件之前稍微增加响应。
将subscribe
视为可观察对象的“路的尽头” ,但是您可以随时将可观察对象传递给任意数量的订阅者,并随时对响应执行不同的操作使用管道。
使用不同的运算符更改不同订户的可观察对象的响应的示例:StackBlitz
在您的代码中尝试如下操作:
组件
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);
}