Как получить доступ к массиву внутри объекта с помощью http Angular? - PullRequest
0 голосов
/ 25 апреля 2020

У меня следующая структура дб. json

{
    "teams": [
        ...
    ],
    "matches": [
        { // matchday

            "id": "4b6023d0-8657-11ea-ab9d-57972c99f38c",
            "matches": [
                {
                    ...
                    "id": "4b604ae0-8657-11ea-ab9d-57972c99f38c"
                },
                ...
            ]
        },
        {...},
        {...},
    ]
}

Как мне обновить соответствие с идентификатором?

Я пробовал это

const MATCHES_API = '/api/matches';

editMatch(match: Match, matchday: Matchday): Observable<Match> {
    return this.http
        .put(`${MATCHES_API}/${matchday.id}/matches/${match.id}`, match)
        .map((response: Response) => response.json());
}

Также, когда я набрал /api/matches/${matchday.id}/matches/${match.id}, он каким-то образом вернул меня к /api/matches/.

Как мне добраться до совпадения здесь?

Обновление: класс компонента где я пытаюсь это реализовать

import { Component, OnInit } from '@angular/core';
import { PremierLeagueService } from '../../premier-league.service';
import { Matchday } from '../../models/matchday.interface';
import { Match } from '../../models/match.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"
                (submitScore)="submitScore($event)"
                (getMatchday)="getMatchday($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);
    }

    submitScore(match: Match) {
        this.premierLeagueService
            .editMatch(match)
            .subscribe((data: Match) => {
                this.matches.forEach((matchdayToCheck: Matchday) => {
                    matchdayToCheck.matches.forEach((matchToCheck: Match) => {
                        if (matchdayToCheck.id === match.id) {
                            matchToCheck = Object.assign({}, matchToCheck, match);
                        }
                    })
                })
            })
    }

     getMatchday(matchday: Matchday) {
         console.log(matchday);
         this.currentMatchday = matchday;
     }
}

Это то, что я получаю, когда пытаюсь отредактировать матч (добавить счет матча)

enter image description here

Я пытался получить доступ к matches array в первый matchday

http://localhost:4000/api/matches/4b6023d0-8657-11ea-ab9d-57972c99f38c

http://localhost:4000/api/matches/${matchday.id}

Доступ к первому игровому дню через идентификатор

Accessed first matchday via ID Как вы можете видеть , matchday имеет ID и matches array

Попытка получить доступ к совпадению

http://localhost:4000/api/matches/4b6023d0-8657-11ea-ab9d-57972c99f38c/4b604ae0-8657-11ea-ab9d-57972c99f38c

http://localhost:4000/api/matches/${matchday.id}/${match.id}

, которое возвращает мне это enter image description here

Обновление 2.0:

Вот так моя локальная БД подключается через веб-пакет

devServer: {
    contentBase: cwd,
    compress: true,
    inline: true,
    hot: true,
    port: 4000,
    publicPath: '/build/',
    quiet: true,
    historyApiFallback: true,
    setup: function (app) {
      app.use('/api', jsonServer.router('db.json'));
    },
    stats: {
      chunks: false,
      chunkModules: false
    }
  },

1 Ответ

0 голосов
/ 25 апреля 2020

если вы используете простой json сервер, что-то вроде this

, он должен работать по этому URL

`${MATCHES_API}/{match.id}`
const MATCHES_API = '/api/matches';

editMatch(match: Match, matchday: Matchday): Observable<Match> {
    return this.http
        .put(`${MATCHES_API}/{match.id}`, match)
        .map((response: Response) => response.json());
}
...