0

I am creating an angular application that contains a game Board component, a Game service, and a Piece interface.

Piece.interface.ts

export interface Piece {
    id: number,
    number: number,
    icon: string,
    value: number
}

Game.service.ts

import { ThisReceiver } from "@angular/compiler";
import { Injectable } from "@angular/core";
import { Piece } from "../models/Piece.model";

@Injectable({
    providedIn: 'root'
})

export class GameService {
    pieces: Piece[] = [
        {
            id: 1,
            number: 1,
            icon: 'checkmark',
            value: 111
        },
        {
            id: 2,
            number: 1,
            icon: 'checkmark',
            value: 111
        },
        {
            id: 3,
            number: 2, 
            icon: 'anchor',
            value: 222
        },
        {
            id: 4,
            number: 2,
            icon: 'anchor',
            value: 222
        },
        {
            id: 5,
            number: 3, 
            icon: 'moon',
            value: 333
        },
        {
            id: 6,
            number: 3,
            icon: 'moon',
            value: 333
        }
    ]

    solvedPieces: Piece[] = [];

    shufflePieces(){
        this.pieces.sort(() => Math.random() - 0.5);
        console.log('done shuffling');
    }
}

In the board component, I inject the game service and display the pieces through a console log.

export class Board implements OnInit{
    constructor(private gameService: GameService){

    }

    data: Piece[] = [];
    ngOnInit(): void {
        this.data = this.gameService.pieces;
        console.log(this.data);
        this.gameService.shufflePieces();
        this.data=this.gameService.pieces;
        console.log(this.data)
    }
}

But when you inspect the logs, you can see that even in the first log, the pieces are shuffled. When you remove the shuffle function, both calls display the pieces array in order. So why am I not seeing the array first in order and then shuffled in my console logs?

I've recreated the issue in stackblitz: Full Screen Demo and Editor URL

game data

onTheInternet
  • 6,421
  • 10
  • 41
  • 74
  • 1
    Does this answer your question? [console.log() shows the changed value of a variable before the value actually changes](https://stackoverflow.com/questions/11284663/console-log-shows-the-changed-value-of-a-variable-before-the-value-actually-ch). Try logging `JSON.stringify(this.data)` to see the point-in-time value (or better yet, use [`debugger`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger) instead of relying on logs to debug). – D M May 24 '22 at 14:23
  • 1
    Yes. This is exactly it. Seems this question is a repeat. Thank you for the link. – onTheInternet May 24 '22 at 14:27

0 Answers0