При инициализации MatchComponent я хочу сделать 1. Получить запрос на получение объекта Match (объект Match имеет идентификатор playerID члена) 2. Получить запрос на получение Players (на основе ID игрока в объекте Match)
Из-за асинхронной связи мой код ниже не работает. Как я могу справиться с этим?
match.component.ts
@Component({
selector: 'app-match',
templateUrl: './match.component.html',
styleUrls: ['./match.component.css']
})
export class MatchComponent implements OnInit {
match: Match;
players: Player[];
constructor(private matchService: MatchService,
private playerService: PlayerService,
private route: ActivatedRoute) { }
ngOnInit() {
this.loadData();
}
loadData(): void {
const matchID = +this.route.snapshot.paramMap.get('id');
this.getMatchByUniqueID(matchID); // first get request
this.match.playerIDs.forEach(id => {
this.getPlayerByUniqueID(id); // get requests that can only work when the match object is set correctly
});
}
// ---------------------------------------------------------
// HTTP ----------------------------------------------------
// ---------------------------------------------------------
getMatchByUniqueID(id: number): void {
this.matchService.getMatch(id)
.subscribe(match => {
if (match.status === 'SUCCESS') {
this.match = Object.setPrototypeOf(match.data, Match.prototype);
}
});
}
getPlayerByUniqueID(id: number): void {
this.playerService.getPlayer(id)
.subscribe(player => {
if (player.status === 'SUCCESS') {
this.players.push(Object.setPrototypeOf(player.data, Player.prototype));
}
});
}
updateMatch(match: Match): void {
console.log('update');
this.matchService.updateMatch(match)
.subscribe(() => this.match);
}
}
match.ts
export class Match {
//...
playerIDs: number[]; /// IDs of players playing this match
//...
}
match.service.ts
import { Match } from './match';
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpHandler } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
import { HttpResponseType } from './http.response';
@Injectable({
providedIn: 'root'
})
export class MatchService {
private matchesURL = 'http://localhost:8080/matches';
httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
constructor(private http: HttpClient) { }
getMatch(id: number): Observable<HttpResponseType<Match>> {
const url = `${this.matchesURL}/${id}`;
return this.http.get<HttpResponseType<Match>>(url)
.pipe(
// tap(_ => this.log(`fetched hero id=${id}`)),
catchError(this.handleError<HttpResponseType<Match>>(`getUser id=${id}`))
);
}
/** PUT: update the match on the server */
updateMatch(match: Match): Observable<any> {
return this.http.put(this.matchesURL + '/' + match.uniqueID, match, this.httpOptions).pipe(
// tap(_ => this.log(`updated user id=${user.id}`)),
catchError(this.handleError<Match>('updateMatch'))
);
}
// ...