1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Why my functions disappears from objects when I pass them? Angular, typescript

Discussão em 'Angular' iniciado por mtt, Setembro 2, 2025.

  1. mtt

    mtt Guest

    I've been making a simple Casino Game, where user can buy for example profile pictures from the shop, all items are stored in array, it is looking like that:

    shopItems = [{
    type: 'Profile Photo',
    name: 'Hugo',
    price: 50,
    bought: false,
    action: () => {
    this.profilePhotos[2].bought = true;
    }
    },
    {
    type: 'Profile Photo',
    name: 'Philips',
    price: 100,
    bought: false,
    action: () => {
    this.profilePhotos[3].bought = true;
    }
    },
    {
    type: 'Profile Photo',
    name: 'Michael',
    price: 200,
    bought: false,
    action: () => {
    this.profilePhotos[4].bought = true;
    }
    }
    ...


    function to buy items:

    buyItem(shopItem) {
    console.log(shopItem)
    if (this.updatePoints() >= shopItem.price) {
    shopItem.bought = true
    shopItem.action()
    }
    }


    ^These two fragments of code are in profile.service.ts and this in profile.component.ts:

    buyItem(shopItem) {
    console.log(shopItem)
    this.profileService.buyItem(shopItem)
    }


    its being invoke when user clicks 'unlock' button (profile.component.html):

    <div class="shop" *ngIf="shopOpened">
    <div class="shop-items">
    <div class="shop-item" *ngFor="let shopItem of shopItems">
    <div class="type">{{shopItem.type}}</div>
    <div class="name">{{shopItem.name}}</div>
    <div class="shop-item-price">{{shopItem.price}}</div>
    <div class="buy-button" (click)="buyItem(shopItem)" *ngIf="!shopItem.bought">UNLOCK</div>
    </div>
    </div>
    <div class="exit-button" (click)="toogleShopOpened()">EXIT</div>
    </div>


    And here is the issue: Every time when I click UNLOCK, nothing happens, action() is not being invoked because it doesn't exist: [​IMG]

    I don't know if its relevant but here are places when I access local storage (profile.service.ts):

    constructor() {
    this.getData()
    }


    and in resetGame(): (resetGame is being invoke when the game is played first time as well)

    resetGame() {
    this.saveData()
    this.getData()
    }
    saveData() {
    localStorage.setItem('profileService', JSON.stringify(this));
    }
    getData() {
    if (localStorage.getItem('profileService') !== null) {
    Object.assign(this, JSON.parse(localStorage.getItem('profileService')));
    }
    }


    I've checked local storage and I can't see my functions as well: [​IMG] just as if browser doesn't see 'action'. I've tried two different browser and delete local storage, nothing helped.

    Continue reading...

Compartilhe esta Página