Я работаю над своим приложением в премьер-лиге, где вы можете создавать свои команды, добавлять результаты матчей, которые закончились, и видеть обновленные данные команд в таблице, где команды сортируются в соответствии с правилами Премьер-лиги .
Проблема:
У меня проблема с обновлением команд после каждого матча. Когда я нажимаю, чтобы обновить определенное совпадение, обновляются данные матча, а затем данные домашней и выездной команд. Но когда я начинаю очень быстро обновлять свои матчи (выставляя счет на веб-сайте), http-запрос, который должен обновить мои команды, перестает работать. Однако, если я обновляю каждое совпадение медленно, все работает как надо.
Поэтому мой вопрос: почему не работают запросы HTTP PUT, которые должны обновлять мои команды, когда я обновляю совпадения быстро?
Я использую Локальный JSON Сервер для хранения моих данных. Ссылка на проект
match-item.component.ts
export class MatchItemComponent implements OnInit {
constructor(private premierLeagueService: PremierLeagueService) {}
ngOnInit() {
this.premierLeagueService
.getAllTeams()
.subscribe((data: Team[]) => {
this.teams = data;
this.homeTeam = this.teams.filter((team: Team) => team.id === this.match.homeTeamID)[0];
this.awayTeam = this.teams.filter((team: Team) => team.id === this.match.awayTeamID)[0];
});
}
@Input()
match: Match;
@Input()
matchday: Matchday;
@Input()
teamIndex: number;
@Input()
teamAmount: number;
@Output()
editedMatchday: EventEmitter<Matchday> = new EventEmitter<Matchday>();
teams: Team[];
homeTeam: Team;
awayTeam: Team;
settingScore: boolean = false;
submittedScore: Match = {...this.match};
setHomeScore(score: number) {
this.submittedScore.homeTeamScore = score;
}
setAwayScore(score: number) {
this.submittedScore.awayTeamScore = score;
}
setScore() {
if (this.submittedScore.homeTeamScore && this.submittedScore.awayTeamScore) {
this.match = { ...this.match, ...this.submittedScore };
this.updateTeams();
this.matchday.matches = this.matchday.matches.map((el: Match) => {
if (el.id === this.match.id) {
el = Object.assign({}, el, this.match);
}
return el;
})
this.editedMatchday.emit(this.matchday);
}
}
toggleSettingScore() {
this.settingScore = !this.settingScore;
}
updateTeams() {
this.homeTeam.gamesPlayed++;
this.awayTeam.gamesPlayed++;
// result
if (this.match.homeTeamScore > this.match.awayTeamScore) {
this.homeTeam.gamesWon++;
this.awayTeam.gamesLost++;
this.homeTeam.points += 3;
} else if (this.match.homeTeamScore === this.match.awayTeamScore) {
this.homeTeam.gamesDrawn++;
this.awayTeam.gamesDrawn++;
this.homeTeam.points++;
this.awayTeam.points++;
} else {
this.homeTeam.gamesLost++;
this.awayTeam.gamesWon++;
this.awayTeam.points += 3;
}
// goals
this.homeTeam.goalsScored += +this.match.homeTeamScore;
this.homeTeam.goalsConceded += +this.match.awayTeamScore;
this.awayTeam.goalsScored += +this.match.awayTeamScore;
this.awayTeam.goalsConceded += +this.match.homeTeamScore;
this.premierLeagueService
.editTeam(this.homeTeam)
.subscribe((data: Team) => {
this.teams = this.teams.map((team: Team) => {
if (team.id === this.homeTeam.id) {
team = Object.assign({}, team, this.homeTeam);
}
return team;
})
})
this.premierLeagueService
.editTeam(this.awayTeam)
.subscribe((data: Team) => {
this.teams = this.teams.map((team: Team) => {
if (team.id === this.awayTeam.id) {
team = Object.assign({}, team, this.awayTeam);
}
return team;
})
})
}
}
league-match.component.ts
import { Component, OnInit } from '@angular/core';
import { PremierLeagueService } from '../../premier-league.service';
import { Matchday } from '../../models/matchday.interface';
import { Match } from '../../models/match.interface';
import { Team } from '../../models/team.interface';
@Component({
selector: 'league-matches',
styleUrls: ['league-matches.component.scss'],
template: `
<div
class="matchday"
*ngFor="let matchday of matches; let i = index">
<h2>Matchday {{ i + 1 }}</h2>
<match-item
*ngFor="let match of matchday.matches; let i = index; let c = count"
[match]="match"
[matchday]="matchday"
[teamIndex]="i"
[teamAmount]="c"
(editedMatchday)="editMatchday($event)">
</match-item>
</div>
`
})
export class LeagueMatchesComponent implements OnInit{
constructor(private premierLeagueService: PremierLeagueService) {}
matches: Matchday[];
currentMatchday: Matchday;
ngOnInit() {
this.premierLeagueService
.getAllMatchdays()
.subscribe((data: Matchday[]) => this.matches = data);
}
editMatchday(matchday: Matchday) {
this.premierLeagueService
.editMatchday(matchday)
.subscribe((data: Matchday) => {
this.matches = this.matches.map((el: Matchday) => {
if (el.id === matchday.id) {
el = Object.assign({}, el, matchday);
}
return el;
})
})
}
}
premier-league.service.ts
getAllTeams(): Observable<Team[]> {
return this.http
.get(TEAMS_API)
.map((response: Response) => response.json())
.catch((error: any) => Observable.throw(error.json()));
}
editTeam(team: Team): Observable<Team> {
return this.http
.put(`${TEAMS_API}/${team.id}`, team)
.map((response: Response) => response.json())
.catch((error: any) => Observable.throw(error.json()));
}
getAllMatchdays(): Observable<Matchday[]> {
return this.http
.get(MATCHES_API)
.map((response: Response) => response.json())
.catch((error: any) => Observable.throw(error.json()));
}
editMatchday(matchday: Matchday): Observable<Matchday> {
return this.http
.put(`${MATCHES_API}/${matchday.id}`, matchday)
.map((response: Response) => response.json())
.catch((error: any) => Observable.throw(error.json()));
}
интерфейсы
export interface Team {
name: string,
club: Club,
gamesPlayed: number,
gamesWon: number,
gamesDrawn: number,
gamesLost: number,
goalsScored: number,
goalsConceded: number,
points: number,
id: number
}
export interface Match {
homeTeamID: number,
awayTeamID: number,
venue: string,
city: string,
homeTeamScore?: number,
awayTeamScore?: number,
id: number
}
export interface Matchday {
id: number,
matches: Match[]
}
export interface Club {
clubName: string,
logoURL: string,
venue: string,
city: string
}