[英]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.