首页 文章

Angular - 如何从另一个observable返回一个observable

提问于
浏览
0

我有一个订阅服务中的observable的组件 . 该方法反过来订阅不同服务中的可观察对象 . 我想将一个数组从最后一个服务传递回第一个服务,然后将该数组传递回组件 . 更具体地说,该组件调用其本地服务,然后该服务调用使用http客户端访问我的数据库的数据服务 . http客户端正在运行,数据服务将数组返回到本地服务 . 本地服务接收数组,但我无法弄清楚如何将该数组作为observable传递回组件 . 以下是短代码块:

零件:

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);

}

1 回答

  • 0

    您在足球服务中使用 subscribe . 您要做的是从您的数据服务中传回observable,并让您的足球服务稍微增加响应,然后再将其传递回您的组件 .

    subscribe 视为您的observable的 "end of the road" ,但您可以将observable传递给任意数量的订阅者,并使用管道随时对响应执行不同的操作 .

    使用不同运算符更改不同订阅者的observable响应的示例: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
        }
      );
    

    Soccer Service

    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;
        })
      );
    

    Data Service

    getPlayers(id): Observable<Player[]> {
        return this.http.get<Player[]>(`apiRootCustom/GetPlayers/${id}`, httpOptions);
      }
    

相关问题