初始化MatchComponent时,我想做 1.获取请求以获取Match对象(Match对象具有成员playerID) 2.获取请求以获取玩家(基于Match对象中的玩家ID)
由于异步通信,我的以下代码无法正常工作。我该如何处理?
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'))
);
}
// ...