初始化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'))
);
}
// ...
答案 0 :(得分:1)
如果我了解您的需求,那么您想使用请求1中的数据发出请求2。
这可以通过RxJs switchMap
运算符轻松完成。
您需要的只是
// First you pipe to the source observable which GETs the data you need
this.firstRequest$.pipe(
// you may apply a filter() pipe which will pass data forth if it returns true
// like filter(res => res.status === 'SUCCESS')
// Then you call method which receives some needed data for second request
// and returns observable of 2nd request
switchMap(res => this.secondRequest(res.id))
).subscribe(res => {
// process the result of 2nd request
});
这是一个小例子
https://stackblitz.com/edit/rxjs-47hmp1?devtoolsheight=60
import { of } from 'rxjs';
import { map, filter, switchMap } from 'rxjs/operators';
// Here we get a source observable
function getFirstObservable() {
return of({
data: {
id: 3
},
status: 'SUCCESS',
});
}
// This is a second source which requires some data to receive first
function getSecondObservable(id: number) {
return of('I was called with id ' + id);
}
getFirstObservable().pipe(
// filter allows emmited values to pass only when resolves to true
filter(response => response.status === 'SUCCESS'),
// Allows us to subsribe to the observabe returned by callback when
// source observable emits value
switchMap(response => getSecondObservable(response.data.id))
).subscribe(result => {
console.log(result);
// handle result
// here goes the result of a second observable when and only when second observable
// emmits value
}, err => {
// handle error logic
})
答案 1 :(得分:0)
只有在第一个调用完成后才进行后续的依赖请求-使用http请求返回的Observable来执行此操作。这使您可以按所需顺序链接请求。
loadData(): void {
const matchID = +this.route.snapshot.paramMap.get('id');
this.getMatchByUniqueID(matchID).subscribe(match => { //subscribe to the http observable
if (match.status === 'SUCCESS') {
this.match = Object.setPrototypeOf(match.data, Match.prototype);
}
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): Observable { // <-- note we are returning the observable here
return this.matchService.getMatch(id);
}
getPlayerByUniqueID(id: number): void {
this.playerService.getPlayer(id)
.subscribe(player => {
if (player.status === 'SUCCESS') {
this.players.push(Object.setPrototypeOf(player.data, Player.prototype));
}
});
}
答案 2 :(得分:0)
您需要在match.component.ts中更改您的 loadData 和 getMatchByUniqueID 方法以获得正确的答案。从第一个api调用获取所有数据后,您应该调用 getPlayerByUniqueID 方法。
loadData(): void {
const matchID = +this.route.snapshot.paramMap.get('id');
this.getMatchByUniqueID(matchID);
}
getMatchByUniqueID(id: number): void {
this.matchService.getMatch(id)
.subscribe(match => {
if (match.status === 'SUCCESS') {
this.match = Object.setPrototypeOf(match.data, Match.prototype);
// call the playerByUniqueId from here
this.match.playerIDs.forEach(id => {
this.getPlayerByUniqueID(id);
});
}
});
}