0

我有一个Observable在我的组件中显示的列表。但是当我通过后端更新列表时,列表不会async在我的组件视图中更新..

我的服务(存储列表的位置):

    export class GameService {
      games: Game[] = []
      public gameSubject = new BehaviorSubject<Game[]>(this.games);
      public readonly games$ = this.gameSubject.asObservable();
    
      constructor(private http: HttpClient) {
        this.getAllGames().subscribe(response => this.gameSubject.next(response))
       }
    
      public createGame(game: Game): Observable<Game> {
        const url = 'http://localhost:8080/api/games';
        return this.http.post<Game>(url, game);
      }
    
      public createAndUpdate(game: Game): void { 
        this.createGame(game).subscribe();
        this.getAllGames().subscribe(response => this.gameSubject.next(response))
    
      }
    
      public getGame(id: number): Observable<Game> {
        const url = 'http://localhost:8080/api/games/sessieId' + id;
        return this.http.get<Game>(url);
      }
    
      public getAllGames(): Observable<Game[]> {
        const url = 'http://localhost:8080/api/games';
        return this.http.get<Game[]>(url);
      }
    
    }

component(我显示列表的地方)

     <div fxLayout="column" fxLayoutAlign="center center">
              <ng-template ngFor let-j="index" let-playerA [ngForOf]="gameService.games$ | async">
                <div fxFlex fxLayout="row" *ngIf="j % 3 == 0">
                  <ng-template ngFor let-i="index" let-player [ngForOf]="gameService.games$ | async">
                    <div fxFlex *ngIf="i < j + 3 && i >= j">
                      <mat-card class="player-card">
                        <mat-card-header>   
                          <mat-card-title>{{ player.user }}</mat-card-title>
                        </mat-card-header>
                        <mat-card-content>
                          <img src="assets/pictures/man.png" />
                        </mat-card-content>
                      </mat-card>
                    </div>
                  </ng-template>
                </div>
              </ng-template>
            </div>

我在更新列表(创建新项目)时调用此方法(来自服务的方法):

    public createAndUpdate(game: Game): void { 
        this.createGame(game).subscribe();
        this.getAllGames().subscribe(response => this.gameSubject.next(response))
    
      }

但是我仍然需要刷新页面才能看到更改

4

1 回答 1

0

您必须在完成this.getAllGames()后调用this.createGame(game)才能获得更新的列表。所以你必须把它放在里面,this.createGame(game).subscribe(() => this.getAllGames().subscribe(response => this.gameSubject.next(response)))但这看起来太难看了。正确的方法是

this.createGame(game).pipe(switchMap(() => this.getAllGames())).subscribe(this.gameSubject)

它将发送创建游戏请求,等到在后端创建游戏并将响应发送回前端,然后我们发出请求以获取所有游戏并将它们推送到主题。

于 2020-11-26T23:14:09.643 回答