Search code examples
angularangular-httpclientangular-http

How to access array inside the object with http Angular?


I've got following structure of db.json

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

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

How can I update match with ID?

I've tried this

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());
}

Also when I typed /api/matches/${matchday.id}/matches/${match.id} it returned me to the /api/matches/ somehow.

How can I get to the match here?

Update: component's class, where I try to implement it

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;
     }
}

This is what I get, when I try to edit match (add match score)

enter image description here

I have tried to access matches array in first matchday

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

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

Accessed first matchday via ID

Accessed first matchday via ID As you can see, matchday has ID and matches array

Trying to access match

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

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

which returns me thisenter image description here

Update 2.0:

This is how my local db connected via webpack

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
    }
  },

Solution

  • if you are using simple json server, something like this

    it should work by 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());
    }